代码之家  ›  专栏  ›  技术社区  ›  George Mauer

如何从Owin中间件正确登录用户

  •  0
  • George Mauer  · 技术社区  · 5 年前

    我正在制作自己的系统,以在某些场景中验证jwt令牌。

    当我正确验证了令牌之后

    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源代码方面遇到了困难。我收到这条信息的唯一方法是 IsAuthorized 返回false。但是没有指定角色或用户(很简单 [授权] 下一步() 我可以停止调试器并检查是否有用户标识,以及是否有 IsAuthorized .

    我已经超越了 AuthorizeAttribute 为了放置断点并在调用时可以看到,但是 actionContext 与完全不同的身份 IsAuthorized == false . 这反过来又让我怀疑我是不是在错误地登录用户身份

    所以。。。 我做得对吗?我该怎么办?

    1 回复  |  直到 5 年前
        1
  •  2
  •   Troopers    5 年前

    我从来没有理解过为什么,但在我的情况下,我需要在签到后使机票有效:

    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