Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Security and hardening

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

ErrorSystem.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

Short answer

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. Split the token, decode each header and payload with a base64url-aware routine, and never decode the signature as text.

  • Applies to Node.js 22, .NET 9, .NET 10
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Split the token at its dots and look at each part before decoding it: its length modulo 4, and whether it holds a minus or underscore. A valid token gives exactly three parts.

    TOKEN="header.payload.signature"   # put your real token here
    echo "$TOKEN" | tr '.' '\n' | while read -r p; do
      echo "length=${#p} mod4=$(( ${#p} % 4 )) url_chars=$(echo "$p" | grep -c '[-_]')"
    done
  2. 2Match what you see, then jump to its fix

    1. 1The first step shows url_chars=1 for a segment, and the decoder reports an illegal or non-base-64 character.The segment uses the URL-safe alphabet, which a standard decoder rejectsFix
    2. 2The first step shows mod4=2 or mod4=3 and Convert.FromBase64String throws FormatException.The padding was removed, and the decoder wants a length that divides by 4Fix
    3. 3A dot is reported as an illegal character, or the result of decoding the last segment is unreadable bytes.The whole token, or its signature part, is being decoded as textFix

What does the error look like?

  • System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
  • Convert.FromBase64String throws FormatException on a JWT segment
  • Decoded JWT payload is garbled or not JSON

Cause 1 of 3

The segment uses the URL-safe alphabet, which a standard decoder rejects

1Check

Base64url is base64 with the 62nd and 63rd characters replaced: a minus sign stands for plus and an underscore for slash. A .NET base64 decoder only accepts the standard characters, and RFC 4648 says a decoder must reject characters outside its alphabet.

echo "$TOKEN" | cut -d. -f2 | grep -c '[-_]'

2Fix

Decode with a base64url-aware call. Node.js has a base64url encoding, and .NET 9 and later has the Base64Url class.

// Node.js
const [h, p] = token.split('.');
console.log(JSON.parse(Buffer.from(p, 'base64url').toString('utf8')));

// .NET 9 and later
byte[] bytes = System.Buffers.Text.Base64Url.DecodeFromChars(payloadSegment);
string json = System.Text.Encoding.UTF8.GetString(bytes);

3Verify

The decoded header and payload are JSON objects, with fields such as alg and exp.

console.log(Buffer.from(h, 'base64url').toString('utf8'));

Confirmed by rfc-editor.org

Did this fix it?

Cause 2 of 3

The padding was removed, and the decoder wants a length that divides by 4

1Check

The JWS specification defines base64url with the trailing = characters left out. Convert.FromBase64String throws when the length, ignoring white space, is not zero or a multiple of 4, so a segment that was not padded back is refused.

echo "$TOKEN" | cut -d. -f2 | awk '{ print length($0) % 4 }'

2Fix

Replace - and _ with + and /, add one or two = signs according to the remainder, and then use the standard decoder. A remainder of 1 means the input is malformed and should be rejected.

static byte[] DecodeBase64Url(string s)
{
    s = s.Replace('-', '+').Replace('_', '/');
    switch (s.Length % 4)
    {
        case 0: break;
        case 2: s += "=="; break;
        case 3: s += "="; break;
        default: throw new FormatException("Illegal base64url string");
    }
    return Convert.FromBase64String(s);
}

3Verify

Decoding the payload segment returns bytes that read as JSON.

Console.WriteLine(System.Text.Encoding.UTF8.GetString(DecodeBase64Url(payloadSegment)));

Confirmed by rfc-editor.org

Did this fix it?

Cause 3 of 3

The whole token, or its signature part, is being decoded as text

1Check

A signed JWT is three base64url parts separated by periods: the header, the payload and the signature. The dots are separators, not base64 characters, and the third part is a binary signature, not text. Count the parts and note which one you pass to the decoder.

echo "$TOKEN" | tr '.' '\n' | wc -l

2Fix

Split on the dot first. Decode part 0 and part 1 and read them as UTF-8 JSON. Leave part 2 alone: it is only for signature checking with the key, never for reading.

const [h, p, sig] = token.split('.');
const header  = JSON.parse(Buffer.from(h, 'base64url').toString('utf8'));
const payload = JSON.parse(Buffer.from(p, 'base64url').toString('utf8'));
// sig stays as it is: verify it with a JWT library, do not print it

3Verify

header and payload print as objects, and no decoder ever sees a dot.

console.log(Object.keys(header), Object.keys(payload));

Confirmed by rfc-editor.org

Did this fix it?

How do I stop it coming back?

  • Use a JWT library to read and verify tokens in server code, and keep hand-written decoding for debugging only.
  • Never treat the decoded payload as proof of anything: decoding does not verify the signature.
  • In .NET 9 and later prefer Base64Url over home-grown replace-and-pad code.

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

Next step

Want this handled for good?

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