0

我正在使用 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

有什么建议吗?

4

1 回答 1

1

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

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

_httpClient.DefaultRequestHeaders.Remove("jwtToken"); // new
_httpClient.DefaultRequestHeaders.Add("jwtToken", _tokenHandler.WriteToken(GetJwtToken()));
于 2020-01-24T12:39:12.537 回答