Search code examples
c#asp.net-mvcjwtasp.net-apicontrolleridentitymodel

.NET generating invalid JWT tokens


I am generating a JWT token in my WindowsService using IdentityModel.Tokens.Jwt, like so:

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:

//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:

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. For more details, see https://aka.ms/IdentityModel/PII.]' must have three segments (JWS) or five segments (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?


Solution

  • The JWT token was generated correctly, the problem was in a shared instance of HttpClient. Each consecutive call added to the DefaultRequestHeaders jwtToken value.

    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()));