【问题标题】:.NET Owin Authentication using my own userRepository.NET Owin 身份验证使用我自己的 userRepository
【发布时间】:2017-05-08 21:32:52
【问题描述】:

我正在创建一个新的 Web API,并使用 OAuth2 进行令牌身份验证,使用 UnityResolver 进行 DI。目前我有一些关于如何使用我自己的 userRepository 来验证用户的设计问题。这两天我一直在阅读很多文章,我主要找到的解决方案是实现 IStoredUser、IUser .. 对于这种情况,我认为会有更好的选择。 这是我的代码:

 public class OAuthServerProvider : OAuthAuthorizationServerProvider
{
    IUserAccountService _userAccountService;

    public OAuthServerProvider(IUserAccountService userAccountService)
    {
        _userAccountService = userAccountService;
    }

    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        var ipAddress = HttpContext.Current.Request.UserHostAddress;
        var userAgent = HttpContext.Current.Request.UserAgent;

        var user = await _userAccountService.GetUserByLogin(context.UserName, context.Password, 1, userAgent, ipAddress);

        if (user != null && context.UserName == user.email && context.Password == user.password)
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
            identity.AddClaim(new Claim("username", user.email));
            identity.AddClaim(new Claim(ClaimTypes.Name, user.firstName));
            context.Validated(identity);
        }
        else
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }
    }

}

如您所见,我正在使用 IUserAccountService 来验证用户是否存在于我的数据库中,方法是调用存储过程和 dapper 来调用 SP,在这部分我没问题。当我需要在我的 Startup.cs 中实例化此类时会出现问题

public class Startup
{
    internal IUserAccountService _userAccountService;

    public void Configuration(IAppBuilder app)
    {             
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);  

        var oAuthProvider = new OAuthServerProvider(_userAccountService);

        OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/api/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = oAuthProvider
        };
        app.UseOAuthAuthorizationServer(options);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);
    }
}

由于 IUserAccountService,我将获得一个空对象引用,我尝试将其注入到启动类构造函数中,但它不起作用。

您知道如何通过使用良好实践和 DI 来实施此解决方案吗?

【问题讨论】:

    标签: authentication oauth-2.0 token owin


    【解决方案1】:

    您可能已将 IUserAccountService 定义为每个请求的生命周期范围。 这样IUserAccountService 在Web 请求开始时就被实例化了。 Startup.Configuration() 方法在 oauth 服务器启动时执行,此时没有 web 请求。

    我遇到了类似的问题,但我使用 Autofac 并解决了它,从 OwinContext 获取 Autofac 生命周期范围:

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        ...
        // Get IUserService from AutofacLifetimeScope (e.g. 'AutofacWebRequest')
        var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
        var userService = autofacLifetimeScope.Resolve<IUserService>();
        ...
    }
    

    这样您就可以从 Web 请求生命周期范围内获取 IUserService 实例。

    我不知道你是否可以用 Unity 做类似的事情。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2014-09-15
      • 2016-07-03
      • 2015-08-10
      • 2018-08-30
      • 2015-09-23
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      相关资源
      最近更新 更多