2017-07-25 8 views
0

ASP.NET CoreでJWTベアラ認証を使用するアプリケーションを構築しました。私がいくつかのアクションを実行するために、別のWebAPIコントローラで読み込む必要があるカスタムクレームを定義します。WebAPIコントローラから要求を取得する - JWTトークン

どのように私はこれを達成することができますか?あなたのことができるようにすべきである(それは "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

:(コードが簡素化されました)

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); 

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

    } 

別のコントローラ:どのように私のコードは次のようになり

このあなたのコントローラ内でこのような申し立てを取得する

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

} 

もしあなたが望むのであれば、上記のコードを使用して要求を取得し、次に(例えば)

HttpContext.User.Identity.MethodName(); 
を使用してそれらを取得します。
関連する問題