I used to have a reference to Microsoft.IdentityModel.Tokens.JWT
and everything was working fine.
I updated to use the new System.IdentityModel.Tokens.Jwt
but nothing seems to work now. It cannot find the ValidateToken
method of the JwtSecurityTokenHandler
and the TokenValidationParameters
have no AllowedAudience
, SigningToken
or ValidateExpiration
properties.
What am I missing here? Can anyone provide with a working sample of a JWT validation with this?
My "old" code :
private static void ValidateJwt(string jwt) { var handler = new JWTSecurityTokenHandler(); var validationParameters = new Microsoft.IdentityModel.Tokens.JWT.TokenValidationParameters() { AllowedAudience = "https://my-rp.com", //SigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(myBase64Key)), SigningToken = new X509SecurityToken( X509 .LocalMachine .My .Thumbprint .Find("UYTUYTVV99999999999YTYYTYTY88888888", false) .First()), ValidIssuer = "https://my-issuer.com/trust/issuer", ValidateExpiration = true }; try { var principal = handler.ValidateToken(jwt, validationParameters); } catch (Exception e) { Console.WriteLine("{0}\n {1}", e.Message, e.StackTrace); } Console.WriteLine(); }
Docs say instance members for JwtSecurityTokenHandler are not guaranteed to be thread safe.
Validate JWT Token using Custom Middleware and Custom Authorize Attribute. Below is the custom JWT middleware that validates the token in the request "Authorization" header if it exists. On successful validation, the middleware retrieves that associated user from the database and assigns it to its context.
JWT (JSON web token) has become more and more popular in web development. It is an open standard which allows transmitting data between parties as a JSON object in a secure and compact way. The data transmitting using JWT between parties are digitally signed so that it can be easily verified and trusted.
Use the SigningCredentials class to specify the signing key, signing key identifier, and security algorithms that are used by WCF to generate the digital signature for a SamlAssertion. To set the digital signature details, set the SigningCredentials property of the SamlAssertion class.
We create a TokenHandler which is a .NET Core inbuilt class for handling JWT Tokens, we pass it our token as well as our “expected” issuer, audience and our security key and call validate. This validates that the issuer and audience are what we expect, and that the token is signed with the correct key.
I get the Key from the Token issuer, so I my general assumption is that it's valid, so I tried changing parts of it before using it in the TokenValidationParameters , but regardless of what I do - nothing changes. There's no Exception or error or anything, like the Key is just completely ignored.
The ValidAlgorithms option most probably only checks the header of the token to see whether the algorithm defined there is allowed (the alg claim of the JWT header). When you specify ValidateIssuerSigningKey = true then the default Signing Key validator is run.
When a JwtSecurityToken is validated, claims with types found in this ISet<T> will not be added to the ClaimsIdentity . The default value is ClaimTypeMapping.InboundClaimFilter. Gets or sets the InboundClaimTypeMap which is used when setting the Type for claims in the ClaimsPrincipal extracted when validating a JwtSecurityToken.
After a lot of research and tests, I finally found that some properties names for TokenValidationParameters
had changed and JwtSecurityTokenHandler.ValidateToken()
method signature too.
So here's the modified working version of the above code.
private static void ValidateJwt(string jwt) { var handler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters() { ValidAudience = "https://my-rp.com", IssuerSigningTokens = new List<X509SecurityToken>() { new X509SecurityToken( X509 .LocalMachine .My .Thumbprint .Find("UYTUYTVV99999999999YTYYTYTY88888888", false) .First()) }, ValidIssuer = "https://my-issuer.com/trust/issuer", CertificateValidator = X509CertificateValidator.None, RequireExpirationTime = true }; try { SecurityToken validatedToken; var principal = handler.ValidateToken(jwt, validationParameters, out validatedToken); } catch (Exception e) { Console.WriteLine("{0}\n {1}", e.Message, e.StackTrace); } Console.WriteLine(); }
And for the reference, the JwtSecurityTokenHandler
lives in the System.IdentityModel.Tokens
namespace. Don't forget to add the package "JSON Web Token Handler For the Microsoft .Net Framework 4.5" (version 4.0.0 at the time I write theses lines).
Hope it can save a few hours of search for some of you guys!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With