다음 코드로 JWT를 생성하고 유효성을 검사합니다..net의 JWT 생성 및 유효성 검사에서 "키가 지원되지 않습니다."라는 메시지가 표시됩니다.
static string GenerateToken()
{
var tokenHandler = new JwtSecurityTokenHandler();
var certificate = new X509Certificate2(@"Test.pfx", "123");
var rsa = certificate.GetRSAPrivateKey();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(),
Issuer = "Self",
IssuedAt = DateTime.Now,
Audience = "Others",
Expires = DateTime.MaxValue,
SigningCredentials = new SigningCredentials(
new RsaSecurityKey(rsa),
SecurityAlgorithms.RsaSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
static bool ValidateToken(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
var certificate = new X509Certificate2(@"Test.cer");
var rsa = certificate.GetRSAPublicKey();
var validationParameters = new TokenValidationParameters
{
ValidAudience = "Others",
ValidIssuer = "Self",
IssuerSigningKey = new RsaSecurityKey(rsa)
};
var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken securityToken);
if (principal == null)
return false;
if (securityToken == null)
return false;
return true;
}
이 코드는 .net 표준 2.0 및 net46을 대상으로하는 라이브러리에 있습니다.
.net 핵심 응용 프로그램 2.0 프로젝트에서 라이브러리를 사용할 때 모든 것이 예상대로 작동합니다. 다음과 같은 너겟 패키지를 사용합니다.
- System.IdentityModel.Tokens.Jwt => 5.1.4
- System.Security.Cryptography.Csp => 4.3.0
하지만 .net46 I와 동일한 코드를 빌드 할 때 토큰을 생성 할 때 다음 예외가 발생합니다.
var token = tokenHandler.CreateToken(tokenDescriptor);
System.NotSupportedException 'NotSupported_Method'
의 I 토큰의 유효성을 검사 할 때 다음과 같은 예외가 던져이다.
var principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken securityToken);
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException : 'IDX10503 : 서명 검증에 실패했습니다. 시도한 키 : 'Microsoft.IdentityModel.Tokens.RsaSecurityKey, KeyId : '.