Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NET 8 minimal API: Error in AspNetCore.Authentication.JwtBearer 8.0.0 #52388

Closed
1 task done
true-perfect-code opened this issue Nov 27, 2023 · 8 comments
Closed
1 task done
Assignees
Labels
area-auth Includes: Authn, Authz, OAuth, OIDC, Bearer ✔️ Resolution: Answered Resolved because the question asked by the original author has been answered. Status: Resolved

Comments

@true-perfect-code
Copy link

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

Authentication via JWT in minimal API works with nuget Microsoft.AspNetCore.Authentication.JwtBearer 7.0.145 but not with Microsoft.AspNetCore.Authentication.JwtBearer 8.0.0

Expected Behavior

The error message is Error: response status is 401
content-length: 0
date: Mon,27 Nov 2023 08:51:14 GMT
server: Kestrel
www-authenticate: Bearer error="invalid_token"

The error message can be reproduced via the attached GitHub project by optionally changing nuget from version 7.014 to 8.0.0 and vice versa.

Steps To Reproduce

GitHub Repository: https://github.com/true-perfect-code/WebApiNet8_minimalAPI

Exceptions (if any)

No response

.NET Version

NET 8

Anything else?

No response

@Tratcher Tratcher added area-auth Includes: Authn, Authz, OAuth, OIDC, Bearer and removed area-security labels Nov 27, 2023
@eirikurharaldsson
Copy link

I,m also having this issue with version 8 of AspNetCore.Authentication.JwtBearer, ground cause seems to be in the OpenIdConnect package dependency going from version 6 to 7.

#52330

@dotnet-policy-service dotnet-policy-service bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Feb 6, 2024
@wtgodbe wtgodbe removed the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Feb 6, 2024
@dotnet-policy-service dotnet-policy-service bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Feb 6, 2024
@wtgodbe wtgodbe removed the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Feb 13, 2024
@dotnet dotnet deleted a comment from dotnet-policy-service bot Feb 13, 2024
@dotnet dotnet deleted a comment from dotnet-policy-service bot Feb 13, 2024
@halter73
Copy link
Member

@true-perfect-code https://github.com/true-perfect-code/WebApiNet8_minimalAPI is now returning a 404. Are you still having an issue? If so, can you put the repro app back up?

There was a breaking change in .NET 8 that was announced in https://learn.microsoft.com/en-us/dotnet/core/compatibility/aspnet-core/8.0/securitytoken-events. You can revert to the previous JwtSecurityToken behavior rather than the new JsonWebToken behavior if it's breaking your app. Everything that was supported by JwtSecurityToken should be supported by JsonWebToken, but you may need to update your code following the guidance in the "Recommended action" section of the breaking change announcement.

@halter73 halter73 added the Needs: Repro Indicates that the team needs a repro project to continue the investigation on this issue label Feb 27, 2024
@dotnet-policy-service dotnet-policy-service bot added Needs: Author Feedback The author of this issue needs to respond in order for us to continue investigating this issue. Status: No Recent Activity labels Feb 27, 2024
@true-perfect-code
Copy link
Author

true-perfect-code commented Mar 4, 2024

Hi Stephen (@halter73 ), I'm Justin from perfect-code.

I have looked at the reported problem from Daniel (also from perfect-code) and the problem still exists. Since almost no one else is reporting the same problem, I assume that the error must be ours and we missed to configure the code correctly.

I have created a new project and uploaded it to GitHub. When I use NuGet version 7.0.14, my WebApi (minimal API) runs without any problems:

image

image

image

image

If I then send a query to WebApi Server, I get the answer

image

image

If I now update NuGet to 8.0.2, make the adjustment in the code described in your link and test everything, I get an error message. It does not work.

image

image

image

You can find the project on GitHub at https://github.com/true-perfect-code/JwtBearer_Problem

As written, I assume that something is configured incorrectly here and hope that you can quickly explain this to us so that we can close this item.

Thank you very much
Justin

@dotnet-policy-service dotnet-policy-service bot added Needs: Attention 👋 This issue needs the attention of a contributor, typically because the OP has provided an update. and removed Needs: Author Feedback The author of this issue needs to respond in order for us to continue investigating this issue. Status: No Recent Activity labels Mar 4, 2024
@mkArtakMSFT mkArtakMSFT added investigate and removed Needs: Attention 👋 This issue needs the attention of a contributor, typically because the OP has provided an update. labels Mar 13, 2024
@true-perfect-code
Copy link
Author

Hello @halter73 , is there anything new? Is it a bigger problem after all?

Regards
tpc

@Lorthirash
Copy link

I have the same problem and i can't solve
Here is my code:
https://github.com/Lorthirash/JWTBEARERNET8

it is work jwtbearer version 7 but new 8+ doesn't work.
How can is solve the problem?
please help.

@MackinnonBuck MackinnonBuck removed the Needs: Repro Indicates that the team needs a repro project to continue the investigation on this issue label May 21, 2024
@halter73
Copy link
Member

@true-perfect-code It looks like the issue was an invalid "iat" claim. RFC 7519 Section 4.1.6 states that it "MUST be a number containing a NumericDate value" where "NumericDate" is Unix Time.

https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6

So new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()) should instead be new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()), so "iat": "5/29/2024 10:00:52 PM" becomes "iat": "1717020577"

If you update your appsettings.Development.json to include "Information" level logging for "Microsoft.AspNetCore", you would see the following in the log output when trying to use a token with an invalid "iat" claim:

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: IDX14101: Unable to decode the payload '[PII of type 'Microsoft.IdentityModel.Logging.SecurityArtifact' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' as Base64Url encoded string.
       ---> System.Text.Json.JsonException: IDX11020: The JSON value of type: 'String', could not be converted to 'JsonTokenType.Number'. Reading: 'Microsoft.IdentityModel.JsonWebTokens.JsonWebToken.iat', Position: '52', CurrentDepth: '1', BytesConsumed: '75'.
         at Microsoft.IdentityModel.Tokens.Json.JsonSerializerPrimitives.ReadLong(Utf8JsonReader& reader, String propertyName, String className, Boolean read)
         at Microsoft.IdentityModel.JsonWebTokens.JsonWebToken.CreatePayloadClaimSet(Byte[] bytes, Int32 length)
         at Microsoft.IdentityModel.Tokens.Base64UrlEncoding.Decode[T](String input, Int32 offset, Int32 length, Func`3 action)
         at Microsoft.IdentityModel.JsonWebTokens.JsonWebToken.CreateClaimSet(String rawString, Int32 startIndex, Int32 length, Func`3 action)
         at Microsoft.IdentityModel.JsonWebTokens.JsonWebToken.ReadToken(String encodedJson)
         --- End of inner exception stack trace ---
         at Microsoft.IdentityModel.JsonWebTokens.JsonWebToken.ReadToken(String encodedJson)
         at Microsoft.IdentityModel.JsonWebTokens.JsonWebToken..ctor(String jwtEncodedString)
         at Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.ReadToken(String token, TokenValidationParameters validationParameters)
         --- End of inner exception stack trace ---

The relevant bit here is "The JSON value of type: 'String', could not be converted to 'JsonTokenType.Number'. Reading: 'Microsoft.IdentityModel.JsonWebTokens.JsonWebToken.iat'".

The part about "JWT is not well formed, there are no dots (.)." appears to be a red herring because the token does indeed have dots. Someone has already reported that this seems to get over reported any time there's a failure in JsonWebTokenHandler.ValidateToken at AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet#2058. I'll update that thread with this example and see if we can improve the Exception message.

Copy link
Contributor

This issue has been resolved and has not had any activity for 1 day. It will be closed for housekeeping purposes.

See our Issue Management Policies for more information.

@true-perfect-code
Copy link
Author

@halter73 Thank you very much, it works. Our prediction was correct, it was our mistake. Thank you once again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-auth Includes: Authn, Authz, OAuth, OIDC, Bearer ✔️ Resolution: Answered Resolved because the question asked by the original author has been answered. Status: Resolved
Projects
None yet
Development

No branches or pull requests

9 participants