Created
May 26, 2018 17:52
-
-
Save varunon9/82a1cb94d022cd8266a1c64a3f246f26 to your computer and use it in GitHub Desktop.
Security middleware for authentication using jsonwebtoken. This gist demonstrate its usage in graphql-express server
This file contains 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
const jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens | |
const env = process.env.NODE_ENV || 'development'; | |
const config = require('../config/config.json')[env]; | |
module.exports = { | |
verifyToken: function(req, res, next) { | |
// get token from cookies | |
const token = req.cookies.jwtToken; | |
if (token) { | |
// verifies secret and checks exp | |
jwt.verify(token, config.superSecret, function(err, decoded) { | |
if (err) { | |
//console.error(err); | |
return res.send( | |
'<p>Failed to authenticate token. ' | |
+ 'Click <a href="logout">Logout</a></p>' | |
); | |
} else { | |
// check if email is present | |
if (!decoded.email) { | |
res.redirect('/login'); | |
} else { | |
// if everything is good, save to request for use in other routes | |
req.decoded = decoded; | |
next(); | |
} | |
} | |
}); | |
} else { | |
res.redirect('/login'); | |
} | |
} | |
} | |
// Use it like this | |
// The GraphQL endpoint, using security middleware: verifyToken | |
app.use('/graphql', middlewares.verifyToken, graphqlExpress((req) => ({ | |
schema: schema, | |
context: { | |
user: req.decoded | |
} | |
}))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment