首页 > 解决方案 > OWIN OAuth 中的 Application_PostAuthenticateRequest 等效项

问题描述

为了使我的服务层能够在需要时随时访问当前的用户 ID,我使用了 Thread.CurrentPrincipal。

服务层由两个前端层使用,一个 MVC 应用程序和一个用于移动应用程序的 MVC Web Api。

在 Web 应用程序中,我使用 Forms Authentication 并且 Principal 设置为Application_PostAuthenticateRequest. 它工作正常。

在 web Api 中,我使用 Owin。但是在使用访问令牌对每个请求进行身份验证后,我找不到设置该 Principal 的方法。

当用户通过覆盖GrantResourceOwnerCredentials我的凭据登录时,我可以做到这一点,或者当他通过在同一类中OAuthAuthorizationServerProvider覆盖而使用刷新令牌登录时,我可以做到这一点。GrantRefreshToken

但是我可以在哪里为使用访问令牌自动验证的请求分配它?

注意。我知道在我的 Api 控制器中我可以访问当前用户,并且设置正确,但我不想在每次调用时将它传递给我的服务层。

谢谢。

标签: asp.net-mvcasp.net-web-apioauthowin

解决方案


我找到了如何设置它。

不记名验证不是由OAuthAuthorizationServerProvider. 我必须实现一个 custom OAuthBearerAuthenticationProvider,并覆盖该ValidateIdentity方法:

public class MyBearerAuthenticationProvider : OAuthBearerAuthenticationProvider
{
    public override Task ValidateIdentity(OAuthValidateIdentityContext context)
    {
        Thread.CurrentPrincipal = new Principal(context.Ticket.Identity);
        return base.ValidateIdentity(context);
    }
}

并使用以下方法将该提供程序插入我的应用程序:

OAuthBearerAuthenticationOptions bearerAuthenticationOptions = new OAuthBearerAuthenticationOptions()
{
    Provider = new MyBearerAuthenticationProvider()
};
app.UseOAuthBearerAuthentication(bearerAuthenticationOptions);

不幸的是 Thread.CurrentPrincipal 在我的业务层中为空。我假设令牌验证是在请求执行之外的另一个线程中完成的。所以我必须改变我的方法。


推荐阅读