2017-07-25 51 views
0

我已經構建了一個在ASP.NET Core中使用JWT承載身份驗證的應用程序。在進行身份驗證時,我定義了一些自定義聲明,這些聲明需要在另一個WebAPI控制器中讀取才能執行某些操作。從WebAPI控制器獲取聲明 - JWT令牌,

任何想法我如何實現這一目標?

這是我的代碼看起來像:(代碼已簡化)

public async Task<IActionResult> AuthenticateAsync([FromBody] UserModel user) 
    { 
     .............. 

       var tokenHandler = new JwtSecurityTokenHandler(); 
       var key = Encoding.ASCII.GetBytes(_appSettings.Secret); 
       var tokenDescriptor = new SecurityTokenDescriptor 
       { 
        Subject = new ClaimsIdentity(new Claim[] 
        { 
         new Claim("userSecurityKey", userDeserialized.SecurityKey.ToString()), 
         new Claim("timeStamp",timeStamp), 
         new Claim("verificationKey",userDeserialized.VerificationKey.ToString()) 

        }), 
        Expires = DateTime.UtcNow.AddDays(7), 
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), 
         SecurityAlgorithms.HmacSha256Signature) 
       }; 
       var token = tokenHandler.CreateToken(tokenDescriptor); 
       var tokenString = tokenHandler.WriteToken(token); 

    .................       

    } 

另一個控制器:(它需要讀取 「verificationKey」 要求)

[HttpGet] 
    [Route("getcandidate")] 
    public async Task<IActionResult> GetCandidateAsync() 
    { 

     try 
     { 
      ............  


      var verificationKey = //TODO: GET VerificationKey FROM THE TOKEN 

      var verificationRecord = await service.GetVerificationRecordAsync(verificationKey); 

      ................. 

     } 
     catch (Exception) 
     { 
      return NotFound(); 
     } 
    } 

回答

1

您應該能夠在您的控制器中檢索這樣的索賠

var identity = HttpContext.User.Identity as ClaimsIdentity; 
if (identity != null) 
{ 
    IEnumerable<Claim> claims = identity.Claims; 
    // or 
    identity.FindFirst("ClaimName").Value; 

} 

如果您想要,您可以寫擴展符合使用上面的代碼檢索聲明,然後使用(例如)檢索它們(例如)

HttpContext.User.Identity.MethodName();