依赖注入(使用SimpleInjector)和OAuthAuthorizationServerProvider

时间:2014-09-23 14:22:29

标签: c# asp.net asp.net-mvc dependency-injection simple-injector

依赖注入新手,所以这可能是一件简单的事情,但我已经尝试过并且无法弄明白,我正在使用Simple Injector。

我有一个完全正常使用SimpleInjector的WebApi,现在我想使用OAuth实现安全性。

要做到这一点,我开始学习本教程,这非常有用,但不使用依赖注入

http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

我的global.asax文件看起来像这样,设置依赖注入(完美工作)

protected void Application_Start()
{
    SimpleInjectorConfig.Register();

    GlobalConfiguration.Configure(WebApiConfig.Register);
}

我创建了一个Startup.Auth.cs文件来配置OAuth

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new MyAuthorizationServerProvider() // here is the problem
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

正如我上面评论的那样,MyAuthorizationServerProvider就是问题所在。它需要我通常注入的IUserService参数。我不想清空构造函数,因为我的IUserService也注入了一个存储库。这是文件

public class ApiAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    private IUserService _service;
    public ApiAuthorizationServerProvider (IUserService service) 
    {
         _service = service;
    }

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

    public override async Task GrantResourceOwnerCredentials(
        OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", 
            new[] { "*" });

        IUserService service = Startup.Container.GetInstance<IUserService>();
        User user = _service.Query(e => e.Email.Equals(context.UserName) &&
            e.Password.Equals(context.Password)).FirstOrDefault();

        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);

    }
}

如何使用依赖注入工作?这必须发生很多,必须能够做一些事情来处理它。我确信这很简单,但我还在学习。

4 个答案:

答案 0 :(得分:24)

我花了一些时间来确定是否可以直接使用OAuthAuthorizationServerOptions方法在Owin管道中注册app.Use(),而不是app.UseOAuthAuthorizationServer()这只是一种扩展方法app.Use()app.Use()有一个重载,您可以在其中注册一个可用于构造OAuthAuthorizationServerOptions的委托。

不幸的是,这种努力达到了死胡同,因为看起来即使我们使用委托进行构造,这很可能只会被Owin管道调用一次导致相同的结果,即单例实例OAuthAuthorizationServerOptions的所有依赖关系,因此该类的所有依赖关系也将是单例。

因此,保持工作正常运行的唯一解决方案是,每次调用UserService方法时,都会提取GrantResourceOwnerCredentials()的新实例。

但是要遵循Simple Injector design principles,在ApiAuthorizationServerProvider类中保持对容器的依赖是不好的设计,就像原始代码所示。

更好的方法是使用UserService类的工厂,而不是直接从容器中拉出它。下一个代码显示了如何执行此操作的示例:

首先,清除global.asax文件中的Application_Start()方法,并将所有启动代码放在Owin Startup()方法中。 Startup()方法的代码:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var container = SimpleInjectorConfig.Register();

        GlobalConfiguration.Configure(WebApiConfig.Register);

        Func<IUserService> userServiceFactory = () => 
              container.GetInstance<IUserService>();

        var OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new ApiAuthorizationServerProvider(userServiceFactory)
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

注意我是如何通过将完全配置的Simple Injector容器返回给调用者来更改SimpleInjectorConfig.Register()函数的签名,以便可以直接使用它。

现在更改ApiAuthorizationServerProvider类的构造函数,以便可以注入工厂方法:

public class ApiAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    private Func<IUserService> userServiceFactory;

    public ApiAuthorizationServerProvider(Func<IUserService> userServiceFactory)
    {
        this.userServiceFactory = userServiceFactory;
    }

    // other code deleted for brevity...

    private IUserService userService 
    { 
        get
        {
            return this.userServiceFactory.Invoke();
        }
    }

    public override async Task GrantResourceOwnerCredentials(
        OAuthGrantResourceOwnerCredentialsContext context)
    {
        // other code deleted for brevity...
        // Just use the service like this
        User user = this.userService.Query(e => e.Email.Equals(context.UserName) &&
            e.Password.Equals(context.Password)).FirstOrDefault();

        // other code deleted for brevity...
    }
}

这样,每次调用UserService方法时都会得到一个新的GrantResourceOwnerCredentials()UserService类后面的完整依赖图将遵循您在Simple Injector配置中定义的生命周期,而您只依赖于应用程序的组合根目录中的容器。

答案 1 :(得分:8)

当您从依赖注入开始时,Owin可能不是最友好的API。

我在你的代码中注意到了这一部分:

IUserService service = Startup.Container.GetInstance<IUserService>();

在您了解如何使用构造函数之前,您可能正在执行此操作。但我认为那是你的答案。 OAuthAuthorizationServerProvider是一个单例,因此您的IUserService也将是一个单例,并且此类的所有依赖项也将是单例。

您提到您在用户服务中使用存储库。你可能不希望这个存储库是单例,因为我想这个存储库将使用某种类型的DbContext。

所以中间答案可能就是你已经做出的解决方案。如果您对UseOAuthAuthorizationServer方法的确切做法进行一些研究,也许有更优雅的解决方案。 Katana的源代码可以在这里找到:Katana source code

对于其他asp.net身份类的注册,DSR注释中的链接将为您提供一个良好的起点。

答案 2 :(得分:7)

首先,这是一个迟到的答案。我刚刚写下来,以防其他人遇到类似的问题,并以某种方式将来链接到这个页面(像我一样)。

之前的答案是合理的,但如果服务实际上是按照Web API请求进行注册的话,那么就无法解决问题,我相信如果他们想对UserManager这样的身份框架对象使用依赖注入,人们通常会这样做。

问题是当调用GrantResourceOwnerCredentials时(通常是当人们点击&#39;令牌&#39;端点)时,简单的注入器不会启动api请求生命周期。要解决这个问题,您只需要开始一个。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        //......
        using (Startup.Container.BeginExecutionContextScope())
        {
            var userService= Startup.Container.GetInstance<IUserService>();
            // do your things with userService..
        }
       //.....
    }

使用BeginExecutionContextScope,简单的注入器将启动一个新的上下文范围。但是,请记住它需要明确处理。

答案 3 :(得分:0)

只要您在App_Start conversionHint

中为webapi注册依赖项解析程序

喜欢这个

SimpleInjectorConfig.Register();

如果您使用推荐的GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); 然后,您可以使用依赖项解析程序来获取此服务的新实例,如此

AsyncScopedLifestyle