I have an electron desktop app that communicates with my Node.js API (not express.js tho). The electron app sends access token in a Authorization header, like this: Authorization: Bearer <access_token> . I set it manually for each http request, not a big deal. The access token comes from Auth0. How can I verify this token in my Node.js server?
So, I just have access token string on my API server and would like to verify it somehow.
Do I have to use express-jwt with jwks-rsa? It looks like it is designed to be used with express. I don’t really have a concept of middlewares and req, res, next thing. All I have is an accessToken, I get it from Authorization header.
For Node in particular, I definitely recommend taking a look at express-oauth2-jwt-bearer - Here’s a quick blog post on it as well:
This library makes it easy to validate access tokens tokens included in the authorization header as well as more granular authorization such as checking for specific scopes, claims, etc.
This is what I came up with to verify accessToken. Simple function that takes accessToken as a string and verifies it. Can you confirm if that’s correct and this is what we should do?
import jwt from 'jsonwebtoken';
import jwkToBuffer from 'jwk-to-pem';
type JWKFile = {
keys: jwkToBuffer.JWK[];
};
const ISSUER = 'https://example.com'; // specify real one
export const verifyJwt = (token: string) => {
return new Promise(async (resolve, reject) => {
// make a request to get the JWKs
const jwks = (await (await fetch(`${ISSUER}/.well-known/jwks.json`)).json()) as
| JWKFile
| undefined;
if (!jwks || jwks.keys?.[0] == undefined) {
return undefined;
}
// convert the jwks to a pem string
const pem = jwkToBuffer(jwks.keys[0]);
jwt.verify(
token,
pem,
{
algorithms: ['RS256'],
},
(err, decoded) => {
if (err) {
return reject(err);
}
return resolve(decoded);
},
);
});
};
can somebody help? I have an accessToken string and would like to verify if it’s correct. How can I do this? All the above examples assume that I have express style middleware, but I don’t.