Autofac dependency injection in implementation of OAuthAuthorizationServerProvider

前端 未结 3 1855
陌清茗
陌清茗 2020-12-15 18:24

I am creating a Web Api application and I want to use bearer tokens for the user authentication. I implemented the token logic, following this post and everything seems to w

3条回答
  •  有刺的猬
    2020-12-15 18:58

    I also tried @jumuro answer using the OwinContextExtensions.GetAutofacLifetimeScope that saves my day. Instead of registering the IUserService at runtime, this answer gives an option on validation/creating the instance service after request.

    I added some new answer because I can't comment yet because of my low reputations but added additional guide codes to help someone.

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
    
            try
            {
                if (service == null)
                {
                    var scope = Autofac.Integration.Owin.OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
                    service = scope.Resolve();
                }
                var user = await service.FindUserAsync(context.UserName);
                if (user?.HashedPassword != Helpers.CustomPasswordHasher.GetHashedPassword(context.Password, user?.Salt))
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }
            catch(Exception ex)
            {
                context.SetError("invalid_grant", ex.Message);
                return;
            }
    
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
    
            AuthenticationProperties properties = CreateProperties(context.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(identity);
    
        }
    

提交回复
热议问题