aspnetcore: SecurityTokenMalformedException after updating to .NET 8
Is there an existing issue for this?
- I have searched the existing issues
Describe the bug
I know https://github.com/dotnet/aspnetcore/issues/52191 is about the same error. But in my case, my JWT is created via Keycloak and I can verify it at https://jwt.io/.
This is the error I get after upgrading to .NET 8 and upgrading my package reference to 8.0.0:
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[1]
Failed to validate the token.
Microsoft.IdentityModel.Tokens.SecurityTokenMalformedException: IDX14100: JWT is not well formed, there are no dots (.).
The token needs to be in JWS or JWE Compact Serialization Format. (JWS): 'EncodedHeader.EndcodedPayload.EncodedSignature'. (JWE): 'EncodedProtectedHeader.EncodedEncryptedKey.EncodedInitializationVector.EncodedCiphertext.EncodedAuthenticationTag'.
---> System.ArgumentException: IDX14102: Unable to decode the header '[Security Artifact of type 'Microsoft.IdentityModel.Logging.SecurityArtifact' is hidden. For more details, see https://aka.ms/IdentityModel/SecurityArtifactLogging.]' as Base64Url encoded string.
---> System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. (Parameter 'IDX10820: Invalid character found in Base64UrlEncoding. Character: '32', Encoding: 'Bearer eyJhbGciOiJSUzI1NiI8OeCv-m8PNIUHSFy39iLfOw3vkcA'.')
Expected Behavior
No response
Steps To Reproduce
No response
Exceptions (if any)
No response
.NET Version
No response
Anything else?
No response
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 6
- Comments: 46 (9 by maintainers)
Not sure if it’s the exact same issue, but I was able to resolve this by adding the
Microsoft.IdentityModel.JsonWebTokenspackage.I originally only had
Microsoft.IdentityModel.TokensandMicrosoft.AspNetCore.Authentication.JwtBearer. With all 3 packages I have joy 🎉This is a really nasty issue. Our tokens (which validated fine in jwt.io) were failing to validate for seemingly no reason after upgrading from dotnet 7 to dotnet 8. Even with
JwtBearerOptions.IncludeErrorDetailsset totruethe only info we got waswww-authenticate: Bearer error="invalid_token". Finally, after setting verbose auth logging in appsettings.json:We were able to see the following incredibly misleading message:
This was despite the fact that our tokens definitely had dots. I even double-checked to make sure it wasn’t some weird unicode character that just looked like a dot. Searching the internet for
IDX14100led us to to a couple Stackoverflow posts and eventually this issue page.Stackoverflow suggested setting
JwtBearerOptions.UseSecurityTokenValidatorstotrue, which got our tokens validating again:However, the docs suggest this isn’t as performant as the default of
false.@natelowry 's solution of installing
Microsoft.AspNetCore.Authentication.JwtBearer(which I do not recall being required in dotnet 7) fixed the issue without requiring any changes to theJwtBearerOptions:I think some sort of check needs to be added on startup to make sure that the appropriate package is installed when
JwtBearerOptions.UseSecurityTokenValidatorsis set tofalse, so that others don’t fall into this trap. We wasted days debugging this.Just to add a couple of thoughts here, as I’m battling with JWT authentication since upgrading to 8.x this week.
There doesn’t seem to be any complete end to end official examples of how to implement JWT using the newer
JsonWebTokenThe breaking changes from 7.x -> 8.x were documented, with workarounds (that did not work) and did not contain enough information for users to create an updated end to end solution.
Coupled with the difficulty in debugging the built in solution and the end result is a large number of developers creating workarounds and custom implementations for a complex security protocol, which is supposed to be standardised to stop buggy “roll your owns”.
I’ll be reverting to 7.x after creating my own 8.x implementation, only to find it can’t validate a perfectly valid token (as confirmed by jwt.io). Dead ends everywhere SMH.
These above configuration worked for me.
I was able to solve this by updating this code
to
and here is all dependencies package relate to jwt
I faced the same problem, and now I will describe my solution to the problem. Apparently, this is a bug in the
Microsoft.AspNetCore.Authentication.JwtBearerlibrary at8.0.1version.If you try to validate the token using the standard means that the library implies, you will get an error.
I decided this because the main method of token validation, which the library assumes, produces a similar error when trying to validate a valid JWT token.
Based on what I was able to find on the Internet, the problem manifests itself on .NET Core 8.0, and it can be solved if you use an older version of
System.Textlibrary in the project, but I found another solution.We can write our own validator and use it instead of the standard one.
The validator code that I wrote:
In the end, you only need to connect your own validator.
Thus, we bypassed the error and did not use the deprecated
UseSecurityTokenValidators.Write your thoughts on this, and excuse my English (I used a translator).
I found the solution to this somewhere else but also posting it here:
IdentityModel.Tokens and JsonWebTokens were bugged and incompatible from inside transient packages.
Update them explicitly to latest and hopefully it will work.
Thanks, it’s work in my project
I was able to solve this along @migajek lines:
I was setting the issued at (iat) claim using
DateTime.UtcNow.ToString(). This seemed fine for https://jwt.io but .NET was expecting a number (epoch time). This is in line with the RFC.also getting
JWT is not well formed, there are no dots (.)- the part about missing dots is extremely misleading.the inner exception is more accurate on this - in my case, the issue being the several fields (such as
sub) are numeric, not string.Sorry, I’m not aware of such a sample - someone from the ASP.NET Core team should be able to help you when they come online later today.
I had this issue after bumping some dependencies already on dotnet8. It turns out that my issue was incompatible versions of installed and transitive dependencies in Microsoft.IdentityModel.*. Make sure they’re all the same version.
It seems to me that it was the Microsoft.AspNetCore.Authentication.JwtBearer that was referencing Microsoft.IdentityModel.OpenIdConnect with a different (a lesser major) version compared to the other packages I had installed.
I solved it by explicitly installing the transitive dependent packages with the same version as the other Microsoft.IdentityModel packages I had installed.
Reference to StackOverflow answer
After installing ‘Microsoft.IdentityModel.JsonWebTokens (8.0.2)’
I now have the following packages:
Microsoft.IdentityModel.Tokens (8.0.2), Microsoft.AspNetCore.Authentication.JwtBearer (8.0.8), Microsoft.IdentityModel.JsonWebTokens (8.0.2)
Then, I set ValidateLifetime = false (it was originally true)
it works fine.
@martincostello i was able to create a new JsonWebToken using the jwt i found, so the jwt is indeed well-formed. The error message ids (IDX10820, IDX14102) indicate an error in parsing the jwt header. The error message contains: ‘Bearer eyJhbGciOiJSUzI1NiI8OeCv-m8PNIUHSFy39iLfOw3vkcA’, which seems to indicate the token passed to IdentityModel has the prefix 'Bearer '.
@martincostello can you guide me to a sample code that shows me how to rewrite my entire security to match .NET 8? I mean, instead of me trying to make .NET 8 work for my old way, I want to upgrade to the new
JsonWebToken. But I can’t find a page on the docs with a sample on what should I change.Works fine with me
Certainly! When upgrading from .NET 6 to .NET 8, I encountered an issue related to setting the “issued at” (iat) claim. Initially, I was using
DateTime.UtcNow.ToString(), but I switched toDateTimeOffset.Now.ToUnixTimeSeconds().ToString()to address the issue. 🚀🕰️Just to update, I finally figured out my issue. It seemed that when I retrieve the token string from localstorage in javascript, it comes out with a double quote at start and finish. It seems the PWA retrieving from local storage doesn’t get that.
So I simply added code in my javascript to remove double quotes from the string:
Hopefully this might help someone else.