Skip to content

Instantly share code, notes, and snippets.

@beall49
Last active January 11, 2024 00:03
Show Gist options
  • Save beall49/83bff56edb26012252b419c8aae35a6d to your computer and use it in GitHub Desktop.
Save beall49/83bff56edb26012252b419c8aae35a6d to your computer and use it in GitHub Desktop.
How to validate a jwt in typescript
import { Response, Request, Router } from 'express';
import jwt from 'jsonwebtoken';
import jwksClient from 'jwks-rsa';
const router: Router = Router();
const BEARER = 'Bearer ';
const jwkClient = jwksClient({
strictSsl: true,
jwksUri: process.env['JWK_URL'] //or wherever you have your configs
});
let cert = "";
/**
* Anything on this route, will be intercepted by router.use
* It will try and validate the token
* if it passes, it will move to the actual method ie router.post('/test-auth'
* if not it will return a 401 and never hit the end point
*/
router.use((req, res, next) => {
if (!req.headers.authorization.includes(BEARER)) {
return res.status(401).send({success: false});
} else {
const token = req.headers.authorization.replace(BEARER, '');
const decoded = jwt.decode(token, {complete: true});
if (decoded === null) {
return res.status(401).send({success: false});
}
const payload = decoded.payload;
const header = decoded.header;
const kid = header.kid;
jwkClient.getSigningKey(kid, (err, key) => {
if (err) {
return res.status(401).send({success: false});
}
cert = key.publicKey;
jwt.verify(token, cert, (err, verfied) => {
if (err) {
res.status(401).send({success: false, err: err});
}
//if no err we gud
next();
});
});
}
});
router.post('/test-auth', (req: Request, res: Response) => {
res.status(200).send({success: true, cert: cert});
});
export const VerifyTokenController = router;
@ranjithabb387
Copy link

getting error in imports please help
image

@matty-roses
Copy link

Have you installed the libraries via npm, and are you using ES modules?

@gerardsiles
Copy link

it looks to me that you need to install the types ^^
npm i --save-dev @types/jsonwebtoken

For future reference, if you hover over tthe error you will see the answer.

@FalconFabio
Copy link

import * as jwt from "jsonwebtoken"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment