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.

Discussion: Microsoft.AspNetCore.Authentication.JwtBearer contains absurd amount of black magic

See original GitHub issue

From @ryanelian on August 28, 2016 14:56

I am trying to develop a ASP.NET application using JWT for securing certain routes and then decided that I would use app.UseJwtBearerAuthentication() to make my life easier by not reinventing the wheel. (And so I can use [Authorize] and call it a day)

However, instead of speeding up an entire day of work, I ended up investigating for hours why a perfectly fine Authorization: Bearer insert_jwt_token_here results in 401 Unauthorized response from the server.

The token in question was generated using the trusty jose-jwt and successfully parsed and verified using jwt.io and the jose-jwt itself so I’m quite confident that the token is correct.

After hours of browsing and reading blogs with no avail, I decided to download the source from Release branch directly and perform step by step debugging by putting a breakpoint in JwtBearerHandler. (Curiously, Microsoft.AspNetCore.Authentication failed to compile unless I enable the nightly myget feed for alpha 1.1.0, because Microsoft.Extensions.SecurityHelper.Sources 1.0.0 doesn’t exist in NuGet.)

Surprisingly, the token in question was failed to be validated by the signature validator because of this:

IDX10503: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey , KeyId: 
'.
Exceptions caught:
 'System.ArgumentOutOfRangeException: IDX10603: The algorithm: 'HS256' cannot have less than: '128' bits. KeySize is: '112'.
Parameter name: key.KeySize
   at Microsoft.IdentityModel.Tokens.SymmetricSignatureProvider..ctor(SecurityKey key, String algorithm)
   at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures)
   at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForVerifying(SecurityKey key, String algorithm)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(Byte[] encodedBytes, Byte[] signature, SecurityKey key, String algorithm, TokenValidationParameters validationParameters)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)
'.
token: '{"alg":"HS256","typ":"JWT"}.{"iss":"TAM.Passport","sub":"ryanelian","iat":1472392366,"exp":1472393266,"jti":"9edb6556-dfa8-4d3e-99ee-4517e986bd01","FirstName":"Ryan","LastName":"Elian","Email":"ryan@email.com","EmployeeId":"12345678","Roles":["Administrator","Programmer"]}'

Apparently, my development secret key ACCELISTROCKS! was too short according to the validator. This is quite an undocumented surprise. So I ended up increasing the secret key to ACCELISTROCKSBOOMBOOMFIRE! and the validator works.

However, the token failed to be validated once again:

IDX10208: Unable to validate audience. validationParameters.ValidAudience is null or whitespace and validationParameters.ValidAudiences is null.

   at Microsoft.IdentityModel.Tokens.Validators.ValidateAudience(IEnumerable`1 audiences, SecurityToken securityToken, TokenValidationParameters validationParameters)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateAudience(IEnumerable`1 audiences, JwtSecurityToken securityToken, TokenValidationParameters validationParameters)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext() in D:\VS\TAM.Passport\src\Microsoft.AspNetCore.Authentication.JwtBearer\JwtBearerHandler.cs:line 100

I didn’t remember asking the TokenValidationParameters to validate Audience…

var tokenValidationParameters = new TokenValidationParameters
{
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = new SymmetricSecurityKey(this.TokenSecretKey),

    ValidateIssuer = true,
    ValidIssuer = TokenService.Issuer,

    ValidateLifetime = true,
    ClockSkew = TimeSpan.Zero
};

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    AutomaticChallenge = true,
    AutomaticAuthenticate = true,
    TokenValidationParameters = tokenValidationParameters,
});

So I ended up putting these into the TokenValidationParameters for good measure:

ValidateAudience = false,
ValidateActor = false,

After I did that, the authorization finally works as intended.

I hope this issue can serve as a mini-blog for other people who are scratching their head over this issue.

Copied from original issue: aspnet/Security#959

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:5
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
leastprivilegecommented, Aug 30, 2016

That said integration with asp.net core 1.0 could be better. We could relax some items if say env.IsDevelopmentEnvironment() was true.

That seems like a really bad idea to me.

Maybe if in development, make it so it can log or emit message containing the reason that the authorization failed? That’d help tremendously.

Doesn’t it do that via logging already?

0reactions
fasas1commented, Jun 18, 2023

Thanks

Read more comments on GitHub >

github_iconTop Results From Across the Web

Bearer was not authenticated. - Microsoft Q&A
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Information: AuthenticationScheme: Bearer was challenged. My json config file.
Read more >
Is auth WAY too hard in .NET? : r/dotnet
I have spent an ungodly amount of hours trying to get auth code flow to work with a simple OICD server, SPA and...
Read more >
Problems with Microsoft.AspNetCore.Authentication. ...
I have had a problem recently in my .NET 6 ASP.NET Core web api project. I use identity server 4 and in the...
Read more >
Using Serilog.AspNetCore in ASP.NET Core ... - Andrew Lock
In this short series I describe how to use Serilog's ASP.NET Core request logging ... everything in the Microsoft namespace of level "Information"...
Read more >
Apps and Services With . NET 7
Since 1993, he has passed more than 80 Microsoft programming ... Authenticating service clients using JWT bearer authentication • 355.
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