示例#1
0
        public static TService Resolve <TService>()
        {
            IOwinContext context = HttpContext.Current.GetOwinContext();
            var          autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context);

            return(autofacLifetimeScope.Resolve <TService>());
        }
示例#2
0
        public static TService Resolve <TService>(IOwinContext context)
        {
            // autofacLifetimeScope is 'AutofacWebRequest'
            // visit http://stackoverflow.com/questions/25871392/autofac-dependency-injection-in-implementation-of-oauthauthorizationserverprovid
            var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context);

            return(autofacLifetimeScope.Resolve <TService>());
        }
示例#3
0
 /// <summary>
 /// Resolve with autofac, or if autofac doesn't exist in the owin context for whatever reason use the provided instance.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="factory"></param>
 /// <param name="instance"></param>
 public static void RegisterAsAutofacResolvableOrUse <T>(this IdentityServerServiceFactory factory, T instance, RegistrationContext context = null) where T : class
 {
     factory.RegisterAsAutofacResolvable <T>(resolveWithOwinContextFunc:
                                             owinContext =>
     {
         var autofac = OwinContextExtensions.GetAutofacLifetimeScope(owinContext);
         return(autofac != null
                 ? autofac.Resolve <T>()
                 : instance);
     },
                                             context: context);
 }
示例#4
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var lifetimeScope    = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
            var queryProcessor   = lifetimeScope.Resolve <QueryProcessor>();
            var commandProcessor = lifetimeScope.Resolve <CommandProcessor>();
            await Task.CompletedTask;

            var loginCommand = new LoginEmployeeCommand(context.UserName, context.Password);
            var loginResult  = commandProcessor.Handle(loginCommand);
            var identity     = new ClaimsIdentity(context.Options.AuthenticationType);

            if (loginResult.Success)
            {
                identity.AddClaim(new Claim(ClaimTypes.Name, loginResult.Result.Name));
                identity.AddClaim(new Claim(ClaimTypes.Role, loginResult.Result.EmployeeGroupId.ToString()));
                identity.AddClaim(new Claim("EmployerId", loginResult.Result.EmployerId.ToString()));

                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password are incorrect");
                return;
            }



            //if (context.UserName == "admin" && context.Password == "admin")
            //{
            //    identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
            //    identity.AddClaim(new Claim(ClaimTypes.Role, "admin2"));
            //    identity.AddClaim(new Claim("username", "admin"));
            //    identity.AddClaim(new Claim(ClaimTypes.Name, "Sourav Mondal"));

            //}
            //else if (context.UserName == "user" && context.Password == "user")
            //{
            //    identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            //    identity.AddClaim(new Claim("username", "user"));
            //    identity.AddClaim(new Claim(ClaimTypes.Name, "Suresh Sha"));
            //    context.Validated(identity);
            //}
            //else
            //{
            //    context.SetError("invalid_grant", "Provided username and password is incorrect");
            //    return;
            //}
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

            if (allowedOrigin == null)
            {
                allowedOrigin = "*";
            }

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var  autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
            var  userManager          = autofacLifetimeScope.Resolve <ApplicationUserManager>();
            User user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            foreach (var role in user.Roles)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, role));
            }
            identity.AddClaim(new Claim("sub", context.UserName));

            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    "userName", context.UserName
                },
                {
                    "isAdmin", user.Roles.Any(t => t == "Administrator").ToString()
                }
            });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
示例#6
0
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var lifetimeScope  = OwinContextExtensions.GetAutofacLifetimeScope(HttpContext.Current.GetOwinContext());
            var queryProcessor = lifetimeScope.Resolve <QueryProcessor>();

            var principal       = actionContext.RequestContext.Principal as ClaimsPrincipal;
            var employeeGroupId = principal
                                  .Claims
                                  .Where(c => c.Type == ClaimTypes.Role)
                                  .Select(c => c.Value)
                                  .DefaultIfEmpty("0")
                                  .FirstOrDefault()
                                  .ToInt();

            queryProcessor.Handle(new HasEmployeeGroupPermissionQuery(employeeGroupId, _permission));

            return(base.IsAuthorized(actionContext));
        }
示例#7
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // get ther current lifetimescope from the requqest
            var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
            var userManager          = autofacLifetimeScope.Resolve <ClientPortalUserManager>();
            ClientPortalUser user    = await userManager.FindByNameAsync(context.UserName);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            if (await userManager.IsLockedOutAsync(user.Id) || user.IsApproved == false)
            {
                context.SetError("invalid_grant", "The user is locked out.");
                return;
            }

            if (!await userManager.CheckPasswordAsync(user, context.Password))
            {
                await userManager.AccessFailedAsync(user.Id);

                if (await userManager.IsLockedOutAsync(user.Id))
                {
                    context.SetError("invalid_grant", "The user is locked out.");
                    return;
                }
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            await userManager.ResetAccessFailedCountAsync(user.Id);

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
            var auth = autofacLifetimeScope.Resolve <IAuthenticationService>();

            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            var user = await auth.SignIn(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);
        }
示例#9
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
            //var AuthenticationService = autofacLifetimeScope.Resolve<IAuthenticationService>();

            //var AuthenticationService = test.Resolve<IAuthenticationService>();

            IAuthenticationService AService = new AuthenticationService();

            if (AService != null)
            {
                var Resp = AService.AuthenticateUser(new AuthenticationDTO()
                {
                    UserName = context.UserName, Password = context.Password
                });

                if (Resp == null || Resp.Result == null || Resp.Status == false || Resp.ResposeID != 0)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));

                if (Resp.Result.Roles != null)
                {
                    foreach (var Role in Resp.Result.Roles)
                    {
                        identity.AddClaim(new Claim("role", Role));
                    }
                }

                context.Validated(identity);
            }
        }
示例#10
0
        public void GetAutofacLifetimeScopeThrowsWhenProvidedNullInstance()
        {
            var exception = Assert.Throws <ArgumentNullException>(() => OwinContextExtensions.GetAutofacLifetimeScope(null));

            Assert.Equal("context", exception.ParamName);
        }