Skip to content

Instantly share code, notes, and snippets.

@marcelobbfonseca
Last active September 18, 2020 12:42
Show Gist options
  • Save marcelobbfonseca/1952ef6e66dcbad61465cd1497ff4a85 to your computer and use it in GitHub Desktop.
Save marcelobbfonseca/1952ef6e66dcbad61465cd1497ff4a85 to your computer and use it in GitHub Desktop.
ExpressJS JWT authentication middleware example
// JWT authentication middleware example.
// Uses RS256 strategy with .pem key pair files.
const fs = require('fs');
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
let publicKey = process.env.PUBLIC_KEY;
try{
const token = req.headers.authorization.split(' ')[1]; //req.headers.token;
console.log(token);
var decoded = jwt.verify(token, publicKey)
console.log(decoded);
next();
}catch(err){
return res.status(401).json({error: err, message: 'Invalid token.'});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment