Search code examples
c#webapibearer-token

validating JWT Bearer token


We have a method called from back office to validate a bearer JWT token by its string token but I'm getting an error when validating.

It's showing this exception:

IDX10503: Signature validation failed. Keys tried: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'. Exceptions caught: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'. token: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.

Code below:

public bool ValidateToken(string authToken)
{
    try
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var validationParameters = GetValidationParameters();

        SecurityToken validatedToken;
        IPrincipal principal = tokenHandler.ValidateToken(authToken, validationParameters, out validatedToken);
    }
    catch(Exception e)
    {
        _MyLogger.Log(StaticVars.ERROR_UP, "validateToken: "+e.Message, "ValidateToken", 80);
        return false;
    }
    return true;
}


private static TokenValidationParameters GetValidationParameters()
{
    return new TokenValidationParameters()
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = false,
        ValidateIssuerSigningKey = false,
        ValidIssuer = "myissuer",
        ValidAudience = "myissuer",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Key..."))
    };
}

Solution

  • By default PII information are hidden, which includes token validation errors( for security measures), however you can enable them in your Development environment by setting this static setting: IdentityModelEventSource.ShowPII = true;

    Once you check the actual error it should hint you on what's wrong with your code or setup.