JWT Unable to decode header as Base64Url encoded string

I have the following code:

public async Task<LoginResult> GenerateJwtTokenAsync(string email, string password)
{
    LoginResult loginResult = await _membershipProvider.Login(email, password);
    if (loginResult.Succeeded)
    {
        var symmetricKey = Convert.FromBase64String(Secret);

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(loginResult.Claims),
            Expires = DateTime.UtcNow.AddDays(1),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature)
        };

        var stoken = _tokenHandler.CreateToken(tokenDescriptor);
        var token = _tokenHandler.WriteToken(stoken);

        // Check token here to see if it works
        var jwtToken = _tokenHandler.ReadToken(token) as JwtSecurityToken;
        loginResult.JwtToken = token;
    }
    return loginResult;
}

public ClaimsPrincipal ValidateJwtToken(string tokenString)
{

    ClaimsPrincipal principal;

    try
    {
        var jwtToken = _tokenHandler.ReadToken(tokenString) as JwtSecurityToken;

        if (jwtToken == null)
        {
            principal = null;
        }
        else
        {
            var symmetricKey = Convert.FromBase64String(Secret);

            var validationParameters = new TokenValidationParameters()
            {
                RequireExpirationTime = true,
                ValidateIssuer = false,
                ValidateAudience = false,
                IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
            };

            SecurityToken securityToken;
            principal = _tokenHandler.ValidateToken(tokenString, validationParameters, out securityToken);
        }
    }
    catch (Exception ex)
    {
        principal = null;
    }

    return principal;
}

The line below reads the token perfectly, however, when I actually read it in the second method, I get an exception.

// Check token here to see if it works
var jwtToken = _tokenHandler.ReadToken(token) as JwtSecurityToken

I confirmed that the two lines are identical, I am very confused why this stops working when I really want to check the token for the life of me. I do not see what I am doing wrong. Any ideas please?

EDIT:

An exception

   "IDX10729: Unable to decode the header 'header' as Base64Url encoded string. jwtEncodedString: 'Token here'."

Stack trace:

   at System.IdentityModel.Tokens.Jwt.JwtSecurityToken.Decode(String[] tokenParts, String rawData)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ReadJwtToken(String token)
   at AuthService.ValidateJwtToken(String tokenString) in AuthService.cs:line 57
+6
source share
3 answers

I had this error and I found that, watching the details of the error, the reason is that the Newtonsoft.Jsondll was not loaded.

System.IdentityModel.Tokens.Jwt.JsonExtensions dll 9.0.0.0, 10.0.0.0. - :

System.ArgumentException: IDX10729:... 'Newtonsoft.Json, Version = 9.0.0.0, Culture = , PublicKeyToken = 30ad4fe6b2a6aeed '

config:

 <runtime>
    <assemblyBinding  xmlns="urn:schemas-microsoft-com:asm.v1">
       <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
+4

, . DLL Newtonsoft.Json .

+1

The JWT library (for example, ValidateToken) requires lines of input tokens, the length of which is divided by 4. You may need to enter the "right pad" to make it divisible by 4; fill sign - equal sign. For your second method, you can verify that "tokenString" is correctly inserted using "=" with this snippet:

 tokenString= tokenString.PadRight(tokenString.Length + (4 - tokenString.Length % 4) % 4, '=');
0
source

Source: https://habr.com/ru/post/1016008/


All Articles