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

标签 c# asp.net-identity owin asp.net-identity-2

我正在构建一个使用 token 进行授权的 web.api 服务。 我遵循了 Dominick Baier 在他的博客中使用的指南 here .

今天我更新了 Owin、Entity Framework 和 ASP.NET web.api 的所有包,我发现很多东西都发生了变化。

我在网上找到了几篇文章(显然没有关于这些主题的文档)并开始转换我的 web.api 服务。

post关于新的 ASP.NET Identity 2.0.0 帮助我转换了几乎所有内容,但现在我陷入了一个简单的愚蠢问题。

我已经按照博客中的建议创建了我的客户 ApplicationUserManagerApplicationDbContext

在我的 Startup 中,我将我的 2 对象与 Owin 上下文相关联:

app.CreatePerOwinContext<ApplicationDatabaseContext>(ApplicationDatabaseContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

我定义了一个自定义的 OAuthAuthorizationServerProvider 因为我想使用 Bearer Authentication:

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

在我的 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;
        ...
        ...
    }
}

但我似乎无法获取我的 ApplicationDbContext。 我能做到这一点的唯一方法是使用我发现通过注册变量的 key :

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

我想知道是否有更简单的方法来实现同样的事情。

最佳答案

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

ApplicationDbContext dbContext = context.OwinContext.Get<ApplicationDbContext>();
ApplicationUserManager userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

关于c# - 在我的自定义 OAuthAuthorizationServerProvider 中的 ValidateClientAuthentication 期间获取 IdentityDbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22975448/

相关文章:

c# - 为什么默认情况下域(业务逻辑)中的不变性不更常见?

c# - Json.NET 如何覆盖通过属性定义自定义 JsonConverter 的类型的序列化?

c# - OWIN 停止服务器\服务?

asp.net - 我如何在此代码中获得 Windows 身份?

asp.net-mvc - 在 Asp.net Core Identity 中通过电话号码注册并登录

asp.net-web-api - Ninject.ActivationException 仅在第一个 Web 请求时抛出(WebAPI 2、OWIN 3、Ninject 3)

c# - 特殊字符正则表达式

c# - 如果关键字之前存在数字,则删除子字符串

c# - OWIN OpenID 提供程序 - GetExternalLoginInfo() 返回 null

asp.net-mvc - Visual Studio 2013 MVC 模板在与 Unity 一起使用时引发错误