Validate a JWT token signature in an asp.net wep api authorization filter

831 views Asked by At

Hi all I am having the hardest time validating an OAUTH JWT. I use Thinktecture Identity Client to get the bearer token and I am trying to validate that token in a Web API authorization filter. OWIN is not an option here and I an not using ASP.NET Core. Here is validation code

var handler = new JwtSecurityTokenHandler();
                var token = handler.ReadToken(actionContext.Request.Headers.Authorization.Parameter) as JwtSecurityToken;
var iss = token.Payload["iss"].ToString();
                var aud = token.Payload["aud"].ToString();
                var exp = int.Parse(token.Payload["exp"].ToString());
                var secret = ConfigurationManager.AppSettings["secret"];
                var signedKey = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
var validationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = signedKey,
                    ValidateIssuer = false,
                    ValidIssuer = iss,
                    ValidateAudience = false,
                    ValidAudience = aud
                };
SecurityToken secTok = null;
                try
                {
                    var principal = handler.ValidateToken(authToken, validationParameters, out secTok);
                }
                catch (Exception ex)
                {
                    var message = ex.GetBaseException();
                }

I get the following response.

IDX10500: Signature validation failed. Unable to resolve SecurityKeyIdentifier: 'SecurityKeyIdentifier
    (
    IsReadOnly = False,
    Count = 1,
    Clause[0] = System.IdentityModel.Tokens.NamedKeySecurityKeyIdentifierClause
    )

Please help Thanks

1

There are 1 answers

0
Gary Archer On

Your key handling looks wrong to me - typically a JWT is signed with a private (asymmetric) key by the Authorization Server (AS). When an API receives a JWT it downloads the token signing public key from the AS's JWKS endpoint - here is an example URL.

Before coding it can be useful to verify steps in an online viewer - this article walks you through the steps - to get the key matching the kid in the header of the JWT. If you can identify this value and supply it to the library you will find that validation works. Out of interest here is some C# code of mine that may help also.