我正在制作自己的系统来在某些情况下验证 jwt token 。
当我正确验证 token 后,我已经
var userIdentity = await user.CreateIdentityAsync(DefaultAuthenticationTypes.ExternalBearer);
owinContext.Authentication.User = new System.Security.Claims.ClaimsPrincipal(userIdentity);
owinContext.Authentication.SignIn(userIdentity);
System.Web.HttpContext.Current.User = owinContext.Authentication.User;
await next()
但这似乎并不能解决身份验证问题,我相信,在 Asp.Net Mvc 级别仍然失败。因为我知道它使用 HttpContext
我尝试在调用 next()
HttpContext.Current.User = new GenericPrincipal(userIdentity, new string[0]);
这让我走得更远,但我似乎仍然收到一个授权错误,它似乎(通过搜索我收到的消息的来源和 where its used )来自 Web Api [Authorize]
属性。
在追踪 .net 源代码方面我遇到了困难。我收到此消息的唯一方法是 if IsAuthorized返回假。但是没有指定角色或用户(只是简单的 [Authorize]
),在前往 next()
之前,我可以停止调试器并检查是否存在用户身份,是的,它IsAuthorized
。
我已经重写了 AuthorizeAttribute
以便放置断点,并且可以看到,在调用它时,我的 actionContext
与一个完全不同的身份关联IsAuthorized == false
。这又让我怀疑我是否登录了错误的用户身份
那么...我我这样做正确吗?我应该做什么?
最佳答案
我从来不明白为什么,但就我而言,我需要在登录后验证票证:
var userIdentity = await user.CreateIdentityAsync(DefaultAuthenticationTypes.ExternalBearer);
ctx.Authentication.SignIn(userIdentity);
AuthenticationTicket ticket = new AuthenticationTicket(userIdentity, null);
ctx.Validated(ticket);
编辑
我并不真正处于同一环境中。就我而言,我有一个继承 Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationProvider
的自定义身份验证提供程序:
public class CustomBearerAuthenticationProvider:OAuthBearerAuthenticationProvider
{
public CustomBearerAuthenticationProvider() : base()
{
this.OnValidateIdentity = (context) => Task.Run(() =>
{
var identity = this.CreateApplicationIdentity(user);
context.OwinContext.Authentication.SignIn(identity);
AuthenticationTicket ticket = new AuthenticationTicket(identity, null);
context.Validated(ticket);
});
}
}
context
的类型为:Microsoft.Owin.Security.OAuth.OAuthValidateIdentityContext
关于asp.net-mvc - 如何从 Owin Middleware 正确登录用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54566167/