在我的自定义OAuthAuthorizationServerProvider中的ValidateClientAuthentication期间获取IdentityDbContext

Lef*_*tyX 2 c# owin asp.net-identity asp.net-identity-2

我正在构建一个使用令牌进行授权的web.api服务.我跟着他的博客使用多米尼克拜尔的准则在这里.

今天我已经更新了Owin,Entity Framework和ASP.NET web.api的所有软件包,我发现很多东西都已经改变了.

我在网上发现了一些文章(显然没有关于这些主题的文档)并开始转换我的web.api服务.

职位有关的新的ASP.NET身份2.0.0帮我把几乎所有转变,但现在我被困在一个简单的愚蠢的事情.

我已经设法按照博客中的建议创建我的客户ApplicationUserManagerApplicationDbContext.

在我的Startup中,我将我的2个对象与Owin Context相关联:

app.CreatePerOwinContext<ApplicationDatabaseContext>(ApplicationDatabaseContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
Run Code Online (Sandbox Code Playgroud)

我已经定义了一个自定义的OAuthAuthorizationServerProvider,因为我想使用Bearer身份验证:

var OAuthOptions = new OAuthAuthorizationServerOptions
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/oauth/Token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),
    Provider = new MyAuthorizationServerProvider(),
    RefreshTokenProvider = new MyRefreshTokenProvider(DateTime.UtcNow.AddHours(8))
};
Run Code Online (Sandbox Code Playgroud)

在我的MyAuthorizationServerProvider中,我已经覆盖了ValidateClientAuthentication,因为我想检查客户端凭据.

一切似乎工作正常,我可以从OwinContext获取我的IAuthenticationManager:

public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
    string clientId = string.Empty;
    string clientSecret = string.Empty;

    if (context.TryGetBasicCredentials(out clientId, out clientSecret))
    {
        IAuthenticationManager manager = context.OwinContext.Authentication;
        ...
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

但我似乎无法获得我的ApplicationDbContext.我能实现这一目标的唯一方法是使用我发现通过注册变量的密钥:

var dbContext = context.OwinContext.Get<ApplicationDbContext>("AspNet.Identity.Owin:OwinWebApiSecurity.Services.ApplicationDatabaseContext, OwinWebApiSecurity, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
Run Code Online (Sandbox Code Playgroud)

我想知道是否有更简单的方法来实现同样的目的.

Lef*_*tyX 9

显然我必须导入Microsoft.AspNet.Identity.Owin命名空间才能访问这些扩展方法.

ApplicationDbContext dbContext = context.OwinContext.Get<ApplicationDbContext>();
ApplicationUserManager userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
Run Code Online (Sandbox Code Playgroud)