I use JWT for my project authentication.
I used .NET 7 and the code shown here works for me correctly.
This code is used for checking if a token exists in the database:
if (!(context.SecurityToken is JwtSecurityToken accessToken) ||
string.IsNullOrWhiteSpace(accessToken.RawData) ||
!await tokenStoreService.IsValidTokenAsync(accessToken.RawData, userId))
{
context.Fail("This token is not in our database.");
return;
}
but when I upgrade my .NET version to 8, now this code doesn’t work anymore.
I searched and I found this article, I don’t know it’s relevant to my question or not.
>Solution :
I searched and I found this article, I don’t know it’s relevant to my question or not.
It is.
The article says that previously (in ASP.NET Core 7), the TokenValidatedContext.SecurityToken property would return a JwtSecurityToken object; but now it returns a JsonWebToken object.
i.e.:
| ASP.NET Core 7 | ASP.NET Core 8 | |
|---|---|---|
JwtBearerEvents.SecurityToken returns: |
System.IdentityModel.Tokens.Jwt.JwtSecurityToken |
Microsoft.IdentityModel.JsonWebTokens.JsonWebToken |
So this code won’t work anymore:
using System.IdentityModel.Tokens.Jwt;
TokenValidatedContext ctx = ...
if( ctx.SecurityToken is JwtSecurityToken jwt )
{
Console.WriteLine( "farts" );
}
You need to change it to test for the new type instead (and remove any references to the now-supplanted System.IdentityModel.Tokens.Jwt.dll library):
using Microsoft.IdentityModel.JsonWebTokens;
TokenValidatedContext ctx = ...
if( ctx.SecurityToken is JsonWebToken jwt )
{
Console.WriteLine( "new and improved farts" );
}
- In your case, you should change your code as follows (and make it more readable by not combining 3 different things in a single
if):- Also, the
JwtSecurityToken.RawDataproperty does not seem to have an equivalent inJsonWebTokensunless it’s the ominously namedUnsafeToStringmethod.
- Also, the
- But I note that the whole point of using JWTs is that applications can delegate trust so they shouldn’t need to verify JWTs themselves beyond cheap-and-quick cryptographic signature verification (so especially nothing as expensive as a round-trip DB lookup!) so something is amiss with your application’s design…
- And if
string.IsNullOrWhiteSpace(accessToken.RawData)thencontext.SecurityTokenwould also benulland yourtokenStoreService.IsValidTokenAsyncwould have to returnfalse– so it’s doubly-redundant.
- And if
if( context.SecurityToken is JsonWebToken jwt )
{
#warning You probably shouldn't need to do any of this:
String rawJwt = jwt.UnsafeToString();
Boolean isValid = await tokenStoreService.IsValidTokenAsync( rawJwt, userId, cancellationToken ).ConfigureAwait(false);
if( !isValid )
{
context.Fail("This token is not in our database.");
return;
}
}