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.
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" );
}
if
):
JwtSecurityToken.RawData
property does not seem to have an equivalent in JsonWebTokens
unless it's the ominously named UnsafeToString
method.string.IsNullOrWhiteSpace(accessToken.RawData)
then context.SecurityToken
would also be null
and your tokenStoreService.IsValidTokenAsync
would have to return false
- so it's doubly-redundant.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;
}
}