question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Bug] AspNetCore 7.0 WebApi Authentication Fails (JWT) - Missing Method

See original GitHub issue

Which version of Microsoft.IdentityModel are you using? 6.27.0 (the latest stable version throws the exception)

Where is the issue?

  • M.IM.JsonWebTokens
  • M.IM.KeyVaultExtensions
  • M.IM.Logging
  • M.IM.ManagedKeyVaultSecurityKey
  • M.IM.Protocols
  • M.IM.Protocols.OpenIdConnect
  • M.IM.Protocols.SignedHttpRequest
  • M.IM.Protocols.WsFederation
  • M.IM.TestExtensions
  • M.IM.Tokens
  • M.IM.Tokens.Saml
  • M.IM.Validators
  • M.IM.Xml
  • S.IM.Tokens.Jwt
  • Other (please describe)

Is this a new or an existing app? The app is in production and I have upgraded to a new version of Microsoft.IdentityModel.*

Repro

builder.Services.AddAuthentication(o => {
        o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(o =>
    {
        o.TokenValidationParameters = new TokenValidationParameters
        {
            ClockSkew = TimeSpan.Zero,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SettingsUtil.Settings.CellaretApiSigningKey)),
            ValidateAudience = true,
            ValidateIssuer = true,
            ValidateIssuerSigningKey = true,
            ValidateLifetime = true,
            ValidAudience = SettingsUtil.Settings.CellaretApiAudience,
            ValidIssuer = SettingsUtil.Settings.CellaretApiIssuer
        };
});

Expected behavior After being issued a valid JWT token (verified by 3rd party site - jwt.io) and my current above code stop working after NuGet package updates, any web api controller with the [Authorize] attribute incorrectly responds with a 401, despite the valid token being passed as “Bearer”. I noticed this issue only after I had updated a number of NuGet packages and finally determined that this package was the culprit through inspection of my console output. It appears the new package is missing a method:

Method not found: 'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration

System.MissingMethodException: Method not found: 'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)'.
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, SecurityToken& signatureValidatedToken)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[7]
      Bearer was not authenticated. Failure message: Method not found: 'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)'.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Information: Bearer was not authenticated. Failure message: Method not found: 'Boolean Microsoft.IdentityModel.Tokens.TokenUtilities.IsRecoverableConfiguration(Microsoft.IdentityModel.Tokens.TokenValidationParameters, Microsoft.IdentityModel.Tokens.BaseConfiguration, Microsoft.IdentityModel.Tokens.BaseConfiguration ByRef)'.
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed. These requirements were not met:
      DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12]
      AuthenticationScheme: Bearer was challenged.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Information: AuthenticationScheme: Bearer was challenged.
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
      Request finished HTTP/1.1 GET https://localhost:7075/helloworld - - - 401 0 - 52.4040ms

Actual behavior A 401 response is returned for all API requests, despite valid JWT tokens being passed.

Possible solution I downgraded to 6.27.0 and this resolved my issue.

Additional context / logs / screenshots / links to code None.

Issue Analytics

  • State:open
  • Created 5 months ago
  • Reactions:4
  • Comments:17 (6 by maintainers)

github_iconTop GitHub Comments

2reactions
GonzaloLebroncommented, Jun 2, 2023

The problem is still happening to me, upgrading from Microsoft.IdentityModel.Tokens 6.27.0 to the latest version. The error I get (when debugging the library) is: IDX10720: Unable to create KeyedHashAlgorithm for algorithm ‘HS256’, the key size must be greater than: ‘256’ bits, key has ‘192’ bits. (Parameter ‘keyBytes’)’ In Microsoft.IdentityModel.Tokens Class: CryptoProviderFactory Method ValidateKeySize(byte[] keyBytes, string algorithm, int expectedNumberOfBytes)

Clearly 24 characters and not 32 SecretKey is my issue “JwtIssuerOptions”: { “SecretKey”: “XXXXXXXXXXXXXXXXXXXXXXXX” },

Even if var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtIssuerOptions.SecretKey)); var signInCredentials = new SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256);

My question is, what this is not a breaking change ? This is not related to missing method

2reactions
kevinchaletcommented, May 25, 2023

@brentschmaltz FYI, I had to release a new OpenIddict version referencing 6.25.1 as I kept receiving similar reports.

Given that it’s not the first time we see such issues in Wilson, you should strongly consider abandoning [InternalsVisibleTo] for your internal helpers or consider them public and avoid breaking changes in minor versions. Alternatively, you could embed your helpers in each assembly to eliminate this kind of problem (it’s the approach used in OpenIddict and it’s always been flawless).

Read more comments on GitHub >

github_iconTop Results From Across the Web

ASP.NET core JWT authentication always throwing 401 ...
I'm trying to implement JWT authentication on my asp.net core webAPI as simply as possible. I don't know what i'm missing but it's...
Read more >
.NET 7.0 + C# - JWT Authentication Tutorial without ASP. ...
In this tutorial we'll go through a simple example of how to implement custom JWT (JSON Web Token) authentication in a .NET 7.0...
Read more >
how do I solve the invalid signature error in jwt ...
1 answer · 1.Create a New Asp.net 7 API application: named "JWTAuth“. · 2.Install the "Microsoft.AspNetCore.Authentication. · 3.Add the LoginDTO.cs ...
Read more >
How To Add JWT Authentication To An ASP.NET Core API
Choose 7.0 for the SDK, and Web API as the Type. Choose no authentication for Auth, because you want to create it yourself....
Read more >
Apply JWT Access Tokens and Refresh Tokens in ASP. ...
Now this is a new tutorial built from the ground up explaining everything about JWT Authentication while using both access and refresh tokens....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found