I am attempting to create a token validation method that returns true if a JWT token is valid based on the signature. I don't think I really need to validate everything in the token but what actually signifies a token is valid after calling ValidateToken()? The existence of a principle? The out referenced token contains certain values? Not sure when to return true from this method.
public bool ValidateToken(string tokenString)
{
var validationParameters = new TokenValidationParameters()
{
ValidIssuer = "My Company",
ValidAudience = ApplicationId,
IssuerSigningKey = JsonWebTokenSecretKey
};
SecurityToken token = new JwtSecurityToken();
var tokenHandler = new JwtSecurityTokenHandler();
var principal = tokenHandler.ValidateToken(tokenString, validationParameters, out token);
return principal != null;
}
I check all of the claims values manually. I've been searching for a definitive answer to your same question but the only thing I have seen is that the ValidateToken function will throw an Exception if something is wrong, so I begin by wrapping the call in a try-catch and return false from the catch.
That's just my "first-pass" at validating the token, though. Afterwards I do a little more heavy lifting to check certain values manually. For example, I make sure that the unique_name value in the claims section actually exists as a user in my database, that the user has not been deactivated, and other proprietary system stuff like that.
The last line,
return validatedToken != null
, is purely superstition on my part. I've never seen the validatedToken be null.