我正在使用 IdentityModel.Tokens.Jwt 在我的 WindowsService 中生成 JWT 令牌,如下所示:
private JwtSecurityToken GetJwtToken()
{
var symmetricSecurityKey = new SymmetricSecurityKey(Convert.FromBase64String(_secretKey));
var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);
return new JwtSecurityToken(
"myIssuer",
expires: DateTime.Now.AddMinutes(15),
signingCredentials: signingCredentials
);
}
然后,我正在编写该令牌JwtSecurityTokenHandler
并将其发送到 WebAPI 控制器的请求中:
//some code...
// _tokenHandler below is a JwtSecurityTokenHandler
_httpClient.DefaultRequestHeaders.Add("jwtToken", _tokenHandler.WriteToken(GetJwtToken()));
HttpResponseMessage response = await _httpClient.GetAsync(url);
//...
在 API 方面,我正在尝试验证令牌:
public bool Authenticate(string token)
{
if (string.IsNullOrEmpty(token))
throw new ArgumentEmptyException(nameof(token));
TokenValidationParameters parameters = new TokenValidationParameters
{
ValidIssuer = "myIssuer",
ValidateIssuer = true,
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Convert.FromBase64String(SecretKey))
};
try
{
new JwtSecurityTokenHandler().ValidateToken(token, parameters, out SecurityToken validatedToken);
return true;
}
catch (SecurityTokenException)
{
return false;
}
}
}
这会引发以下错误:
IDX12741:JWT:'[PII 已隐藏。有关更多详细信息,请参阅 https://aka.ms/IdentityModel/PII。] '必须具有三个段 (JWS) 或五个段 (JWE)。'
还有一个生成令牌的例子,它实际上看起来像一次发送的两个令牌,这让我感到困惑:
eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1Nzk2OTc3NzUsImlzcyI6Im15SXNzdWVyIn0.g9Mw7FijNzAzGofll5E44B8cJtOozln3nUjHKgnkdTs,
eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1Nzk2OTc3ODAsImlzcyI6Im15SXNzdWVyIn0.Noc3lC0h_ryH6axlQJ2Kk2a8wcp5eQ0QhBqidfjuujo
有什么建议吗?