.NET 生成无效的 JWT 令牌

.NET generating invalid JWT tokens

我正在使用 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 is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' must have three segments (JWS) or five segments (JWE).'

还有一个生成的令牌的例子,它实际上看起来像一次发送两个令牌,这让我感到困惑:

eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1Nzk2OTc3NzUsImlzcyI6Im15SXNzdWVyIn0.g9Mw7FijNzAzGofll5E44B8cJtOozln3nUjHKgnkdTs,

eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1Nzk2OTc3ODAsImlzcyI6Im15SXNzdWVyIn0.Noc3lC0h_ryH6axlQJ2Kk2a8wcp5eQ0QhBqidfjuujo

有什么建议吗?

正确生成了 JWT 令牌,问题出在 HttpClient 的共享实例中。添加到 DefaultRequestHeaders jwtToken 值的每个连续调用。

当我添加逻辑以在添加新令牌之前重置值时,它起作用了:

_httpClient.DefaultRequestHeaders.Remove("jwtToken"); // new
_httpClient.DefaultRequestHeaders.Add("jwtToken", _tokenHandler.WriteToken(GetJwtToken()));