asp.net-mvc - 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 控制器中我可以访问当前用户,并且设置正确,但我不想在每次调用时将它传递给我的服务层。
谢谢。
解决方案
我找到了如何设置它。
不记名验证不是由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 在我的业务层中为空。我假设令牌验证是在请求执行之外的另一个线程中完成的。所以我必须改变我的方法。
推荐阅读
- php - 如何使用 Carbon 确定一个月是否已经过去
- c++ - 不存在的行包含在 Visual Studio 2017 中的动态代码覆盖率分析中
- css - CSS使外部元素固定责任
- python - PyMySQL 数据处理到 Python
- azure - 列出提供者资源类型的可用子资源
- asp.net-core - IE11 的 Vuetify/Lib Polyfilling 不起作用 - SCRIPT1002:语法错误
- r - 如何在闪亮的R中显示反应数据框中的最后一个日期条目
- javascript - 如何使用一个按钮来改变其他按钮的样式?
- ios - iOS 13:UIScrollView 不再滚动
- r - 如何用锯齿形或斜线填充 ggplot geom_map 中的 NA 值?