Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Last active August 11, 2017 06:12
Show Gist options
  • Save saiumesh535/8e1841fe99f891ad2ad616371dec639b to your computer and use it in GitHub Desktop.
Save saiumesh535/8e1841fe99f891ad2ad616371dec639b to your computer and use it in GitHub Desktop.
creating and verifying "jsonwebtoken" in express as middleware.
// source : https://www.npmjs.com/package/jsonwebtoken
// check token information at : https://jwt.io/
const jwt = require('jsonwebtoken');
// secret key
const secretKey = 'some secret key';
// this is for verifying and creating token middleware
app.use((req, res, next) => {
// if the requested URL is login then create token otherwise verify
if (req.url.indexOf('login') !== -1) {
const someData = {
clientID: '1233444'
}
// creating web token.
const token = jwt.sign(someData, secretKey, { expiresIn: 60 * 60 });
// now assign that token to some parameter
req.token = token;
next();
} else {
// if the requested URL is not login then verify the token
// you can pass options as json such as ignoreExpiration: true etc..
jwt.verify(req.get('token'), secretKey, { ignoreExpiration: true }, (err, decoded) => {
if (err || decoded.length == 0) {
res.send('Authentication failed')
} else {
// assigning the token data to some parameter to read later
req.authData = decoded;
next();
}
});
}
})
app.get('/login', (req, res) => {
res.json({ token: req.token });
})
app.get('/verify', (req, res) => {
res.json({ data: req.authData });
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment