Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Security and hardening

.NET cannot convert the string to a JwtSecurityToken

ErrorToken handler unable to convert the token to jwt token

Short answer

The handler only accepts a compact JWT: three dot-separated base64url segments for a signed token. Strings with a Bearer prefix, quotes, spaces, an opaque token or a token over the size limit fail. Test the string with CanReadToken to see which it is.

  • Applies to System.IdentityModel.Tokens.Jwt 8.x, .NET 8
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Print the token's length and the number of dot-separated parts, and ask the handler whether it can read it.

    var handler = new JwtSecurityTokenHandler();
    Console.WriteLine($"{token.Length} chars, {token.Split('.').Length} parts, canRead={handler.CanReadToken(token)}");
  2. 2Match what you see, then jump to its fix

    1. 1canRead is false and the string starts with Bearer or contains quotes or whitespaceThe string includes more than the tokenFix
    2. 2Fewer than three parts, or the token comes from a Microsoft API such as GraphThe value is not a JWT at allFix
    3. 3ArgumentException on a token with a very large claims setThe token is longer than the handler's size limitFix

What does the error look like?

  • Token handler unable to convert the token to jwt token
  • SecurityTokenMalformedException

Cause 1 of 3

The string includes more than the token

1Check

CanReadToken matches the string against a pattern of letters, digits, hyphen and underscore separated by dots. A leading scheme word, a space or a quote character fails the match.

Console.WriteLine(token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase));

2Fix

Remove the scheme and trim before reading.

var raw = authorizationHeader.Substring("Bearer ".Length).Trim().Trim('"');
var jwt = handler.ReadJwtToken(raw);

3Verify

CanReadToken now returns true.

Console.WriteLine(handler.CanReadToken(raw));

Confirmed by learn.microsoft.com

Did this fix it?

Cause 2 of 3

The value is not a JWT at all

1Check

Tokens that a Microsoft API receives might not always be a JWT that can be decoded; clients should treat access tokens as opaque.

Console.WriteLine(token.Split('.').Length);

2Fix

Do not parse the token in the client. Send it to the API it was issued for, which validates it, and use the token response metadata for expiry and scopes.

// client: send the string as-is
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

3Verify

The API validates the token and returns data instead of a 401.

curl -i -H "Authorization: Bearer $TOKEN" https://api.example.com/me

Confirmed by learn.microsoft.com

Did this fix it?

Cause 3 of 3

The token is longer than the handler's size limit

1Check

ReadJwtToken throws ArgumentException when the token length is greater than MaximumTokenSizeInBytes, and CanReadToken returns false.

Console.WriteLine($"{token.Length} vs {handler.MaximumTokenSizeInBytes}");

2Fix

Issue a smaller token by putting fewer claims in it; large data belongs behind an API call.

// identity provider: reduce the claims added to the token

3Verify

The read succeeds.

Console.WriteLine(handler.CanReadToken(token));

Confirmed by learn.microsoft.com

Did this fix it?

How do I stop it coming back?

  • Parse the Authorization header in one helper, not in each controller.
  • Keep claims small; put big data behind an API call.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Security

A valid JWT fails to decode because its segments are base64url, not base64

Convert.FromBase64String throws FormatException on a JWT segment

A JWT is three base64url segments joined by dots, and a standard base64 decoder refuses all three differences: base64url uses - and _ instead of + and /, leaves off the = padding, and the dots are not part of any base64 alphabet.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.