A valid JWT fails to decode because its segments are base64url, not base64
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.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.
Fix it fast
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 '[-_]')" done2Match what you see, then jump to its fix
- 1
The 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
The 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
A 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
- 1
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 segmentDecoded 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
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
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 -l2Fix
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 it3Verify
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
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:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
- RaheebA consumer app shipped to both stores from one Flutter codebase on a .NET and Azure back end.
Related fixes
Security
.NET cannot convert the string to a JwtSecurityToken
SecurityTokenMalformedException
The handler only accepts a compact JWT: three dot-separated base64url segments for a signed token.
3 causes, each with a fixSecurity
Entra ID token request fails: the request body must contain the parameter 'grant_type'
AADSTS900144: The request body must contain the following parameter: 'grant_type'.
The token endpoint did not find grant_type in the form body of your POST.
3 causes, each with a fixSecurity
ASP.NET Core cannot create the JWT because the signing key is too short or unusable
IDX10630: The '<key type>' for signing cannot be smaller than '<bits>' bits. KeySize: '<bits>'.
The error happens while the API signs the token, not while it checks one.
3 causes, each with a fixSecurity
AuthenticationException: your certificate validation callback returned false
System.Security.Authentication.AuthenticationException
This message means a validation callback was installed, yours or one a library added, and it returned false.
3 causes, each with a fixSecurity
DelegateAuthenticationProvider no longer exists in the Microsoft Graph .NET SDK
The type or namespace name 'DelegateAuthenticationProvider' could not be found
Microsoft Graph .NET SDK v5 removed DelegateAuthenticationProvider.
3 causes, each with a fixSecurity
jsonwebtoken rejects a token: invalid signature, jwt expired or jwt malformed
JsonWebTokenError: invalid signature
Each message points at a different step.
5 causes, each with a fix