.NET生成无效的JWT令牌

时间:2020-01-22 12:48:54

标签: c# asp.net-mvc jwt asp.net-apicontroller identitymodel

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

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

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

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

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