Skip to content

Instantly share code, notes, and snippets.

@dmytro-kerest
Created March 10, 2020 12:10
Show Gist options
  • Select an option

  • Save dmytro-kerest/93821a555369bf5aa3652168d99551b8 to your computer and use it in GitHub Desktop.

Select an option

Save dmytro-kerest/93821a555369bf5aa3652168d99551b8 to your computer and use it in GitHub Desktop.
jwt middleware
import { Request, Response, NextFunction } from "express";
import * as jwt from "jsonwebtoken";
import config from "../config/config";
export const checkJwt = (req: Request, res: Response, next: NextFunction) => {
const token = <string>req.headers["authorization"].match(/^Bearer (.*)$/)[1];
let jwtPayload;
try {
jwtPayload = <any>jwt.verify(token, config.jwtSecret);
res.locals.jwtPayload = jwtPayload;
} catch (error) {
res.status(401).send();
return;
}
const { userId, username } = jwtPayload;
const newToken = jwt.sign({ userId, username }, config.jwtSecret, {
expiresIn: config.jwtExpirationTimeframe
});
res.setHeader("token", newToken);
next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment