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

非常感謝。這解釋了很多。其實你可以添加它作爲答案。 –