[英].NET generating invalid JWT tokens
I am generating a JWT token in my WindowsService using IdentityModel.Tokens.Jwt, like so:我正在使用 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
);
}
Then, I am writing that token with JwtSecurityTokenHandler
and sending it in a request to a WebAPI controller:然后,我使用
JwtSecurityTokenHandler
编写该令牌并将其发送到 WebAPI 控制器的请求中:
//some code...
// _tokenHandler below is a JwtSecurityTokenHandler
_httpClient.DefaultRequestHeaders.Add("jwtToken", _tokenHandler.WriteToken(GetJwtToken()));
HttpResponseMessage response = await _httpClient.GetAsync(url);
//...
And on the API side, I am trying to validate the token:在 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;
}
}
}
This throws an error below:这会引发以下错误:
IDX12741: JWT: '[PII is hidden.
IDX12741:JWT:'[PII 已隐藏。 For more details, see https://aka.ms/IdentityModel/PII.] ' must have three segments (JWS) or five segments (JWE).'
有关更多详细信息,请参阅https://aka.ms/IdentityModel/PII。] ' 必须具有三段 (JWS) 或五段 (JWE)。
And an example of a generated token, which actually looks like two tokens sent at once, which is baffling me:还有一个生成令牌的例子,它实际上看起来像一次发送两个令牌,这让我感到困惑:
eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1Nzk2OTc3NzUsImlzcyI6Im15SXNzdWVyIn0.g9Mw7FijNzAzGofll5E44B8cJtOozln3nUjHKgnkdTs,
eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1Nzk2OTc3ODAsImlzcyI6Im15SXNzdWVyIn0.Noc3lC0h_ryH6axlQJ2Kk2a8wcp5eQ0QhBqidfjuujo
Any advice?有什么建议吗?
The JWT token was generated correctly, the problem was in a shared instance of HttpClient. JWT 令牌生成正确,问题出在 HttpClient 的共享实例中。 Each consecutive call added to the DefaultRequestHeaders jwtToken value.
每个连续调用都添加到 DefaultRequestHeaders jwtToken 值中。
When I added logic to reset the value before adding new token, it worked:当我在添加新令牌之前添加逻辑来重置值时,它起作用了:
_httpClient.DefaultRequestHeaders.Remove("jwtToken"); // new
_httpClient.DefaultRequestHeaders.Add("jwtToken", _tokenHandler.WriteToken(GetJwtToken()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.