Last active
January 11, 2024 00:03
-
-
Save beall49/83bff56edb26012252b419c8aae35a6d to your computer and use it in GitHub Desktop.
How to validate a jwt in typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
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.
import * as jwt from "jsonwebtoken"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have you installed the libraries via npm, and are you using ES modules?