0

我确实创建了自定义AuthorizeAttribute,该应用程序应处理Jwt不记名令牌,然后创建ClaimsIdentity。但是当我再次发送请求时,无论如何我都看不到授权用户,并且必须再次创建ClaimsIdentity并再次将用户添加到CurrentPricipal。我做错了什么?通过OWIN AuthenticationManager.SignIn添加声明身份不起作用

public class JwtAuthorizeAttribute : AuthorizeAttribute 
    { 
     private readonly string role; 

     public JwtAuthorizeAttribute() 
     { 
     } 

     public JwtAuthorizeAttribute(string role) 
     { 
      this.role = role; 
     } 

     protected override bool IsAuthorized(HttpActionContext actionContext) 
     { 
      var jwtToken = new JwtToken(); 
      var ctx = actionContext.Request.GetOwinContext(); 
      if (ctx.Authentication.User.Identity.IsAuthenticated) return true; 
      if (actionContext.Request.Headers.Contains("Authorization")) 
      { 
       var token = actionContext.Request.Headers.Authorization.Parameter; 
       try 
       { 
        IJsonSerializer serializer = new JsonNetSerializer(); 
        IDateTimeProvider provider = new UtcDateTimeProvider(); 
        IJwtValidator validator = new JwtValidator(serializer, provider); 
        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); 
        IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); 
        var json = decoder.Decode(token, SiteGlobal.Secret, verify: true); 
        jwtToken = JsonConvert.DeserializeObject<JwtToken>(json); 
        if (jwtToken.aud != SiteGlobal.Audience || jwtToken.iss != SiteGlobal.Issuer || role != jwtToken.role) 
        { 
         return false; 
        } 
       } 
       catch (TokenExpiredException) 
       { 
        return false; 
       } 
       catch (SignatureVerificationException) 
       { 
        return false; 
       } 
      } 
      else 
      { 
       return false; 
      } 
      var identity = new ClaimsIdentity("JWT"); 
      identity.AddClaim(new Claim(ClaimTypes.Name, jwtToken.unique_name)); 
      identity.AddClaim(new Claim(ClaimTypes.Role, jwtToken.role)); 
      ctx.Authentication.SignIn(new AuthenticationProperties { IsPersistent = true }, identity); 
      Thread.CurrentPrincipal = new ClaimsPrincipal(identity); 
      HttpContext.Current.User = new ClaimsPrincipal(identity); 
      return true; 
     } 
    } 

回答

0

登录用于创建cookie。你有一个Cookie Auth中间件来处理登录?

+0

不,我正在使用jwt令牌,但看起来像完全混淆了如何在这种情况下创建授权用户。 –

+1

智威汤逊旨在发送和验证每个请求。您的登录电话没有做任何事情,只能使用cookie。 – Tratcher

+0

非常感谢。这解释了很多。其实你可以添加它作为答案。 –