Last active
November 8, 2017 11:09
-
-
Save saiumesh535/b883e93348b96c304d4e22a6fe70983e to your computer and use it in GitHub Desktop.
Creating JWT
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
var express = require('express'); | |
var app = express(); | |
const expressjwt = require('express-jwt') | |
const jsonwebtoken = require('jsonwebtoken'); | |
// this will verify the token before going to actual requested route (middleware) | |
// except the "/login" route every request needs token in header which will look like "Authorization:Bearer eyJh..........." refer image in story | |
app.use(expressjwt({secret: "some key"}).unless({path: ['/', '/login']})) | |
// login user routing | |
app.post('/login', (req, res) => { | |
// creating token with user data "{username: req.body.username}" | |
const token = jsonwebtoken.sign({username: req.body.username}, "some key"); | |
res.status(200).send(token); | |
}) | |
// on user request "/getData" | |
app.get('/getData', (req, res) => { | |
// to retrieve same data which we haved saved during token generation | |
jsonwebtoken.verify(req.get('Authorization').replace("Bearer ", ""), "some key", { | |
ignoreExpiration: true | |
}, (err, data) => { | |
res.status(200).send(data); | |
}) | |
}) | |
// to write you own error message on wrong token | |
app.use(function (err, req, res, next) { | |
// this is for custom message on wrong/no token | |
if (err.name === "UnauthorizedError") { | |
res.status(401).send("No token") | |
} else { | |
// set locals, only providing error in development | |
res.locals.message = err.message; | |
res.locals.error = req.app.get('env') === 'development' ? err : {}; | |
// render the error page | |
res.status(err.status || 500); | |
res.render('error'); | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment