2017-07-25 93 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();