When is JWTSecurityTokenHandler.ValidateToken() actually valid?

99封情书 提交于 2019-11-30 17:20:42

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.

    public static bool VerifyToken(string token)
    {
        var validationParameters = new TokenValidationParameters()
        {
            IssuerSigningToken = new BinarySecretSecurityToken(_key),
            ValidAudience = _audience,
            ValidIssuer = _issuer,
            ValidateLifetime = true,
            ValidateAudience = true,
            ValidateIssuer = true,
            ValidateIssuerSigningKey = true
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        SecurityToken validatedToken = null;
        try
        {
            tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
        }
        catch(SecurityTokenException)
        {
            return false; 
        }
        catch(Exception e)
        { 
            log(e.ToString()); //something else happened
            throw;
        }
        //... manual validations return false if anything untoward is discovered
        return validatedToken != null;
    }

The last line, return validatedToken != null, is purely superstition on my part. I've never seen the validatedToken be null.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!