sheepinwild
sheepinwild

Reputation: 541

How do I verify jwt token with this public key in Node.js?

We have a legacy code that verifies a jwt token with a public key, and it is written in C#. The key is in this format

{
  "keys": [
    {
      "kty": "RSA",
      "kid": "xyz...",
      "n": "abc...",
      "e": "AQAB"
    }
  ]
}

It is deserialised to RSASecurityKey type. The C# then verifies jwt token by assigning the public key to the IssuerSigningKey field.

 TokenValidationParameters validationParams =
     new TokenValidationParameters()
     {
         RequireExpirationTime = true,
         ...
         IssuerSigningKey = **securityKey**,
         ...
     };
 tokenHandler.ValidateToken(jwtToken, validationParams, out securityToken);

Now I want to port this code to Node.JS and I've been studying this method jwt.verify(token, key). The key param is string type. How do make the original key string to a format that is accepted in Node? Thanks

Edit:

Now I managed to get the original key into this format which seems to be the right one.

-----BEGIN PUBLIC KEY----- MIIBI... .... ...........................Tf6LHUDEh/hm 7QIDAQAB -----END PUBLIC KEY-----

I used this library jwk-to-pem to convert it.

Now I run the verify it shows JsonWebTokenError: invalid signature

Is there anything else I'm doing wrong?

Upvotes: 1

Views: 1964

Answers (1)

sheepinwild
sheepinwild

Reputation: 541

Figured this out, if you are not very familiar with Node like me, you'll need to use the jwk-to-pem package to convert it to the pem format.

Make sure your signing key and verifying key are the same. Then the verification shouldn't have any problem.

Upvotes: 2

Related Questions