Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gist for article for jwt implementation.
const jwt = require('jsonwebtoken');
const app = require('express')();
const passport = require('passport');
const LocalStrategy = require('passport-local').Stratergy;
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
// Use Local Startergy for authenticating user
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) {
return done(null, false);
}
return done(null, user);
});
}
));
// Apply passport authentication for getting user payload
app.post('/login', (req, res, next) => {
passport.authenticate('local', (err, userData) => {
if (!userData || err) {
return res.status(404).json({
msg: 'Account not available. Please Sign Up.',
});
}
req.logIn(user, (error) => {
if (error) return next(error);
return res.json({
token: jwt.sign({user: userData}, 'secret'),
});
});
})(req, res, next);
});
// Using passport-jwt stratergy
passport.use(new JwtStrategy({
jwtFromRequest : ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey :'secret',
},
function(jwt_payload, done) {
User.findOne({_id: jwt_payload._id}, function(err, user) {
if (err || !user) {
return done(err, false);
}
if (user) {
return done(null, user);
}
});
}));
// Calling passport authenticate method jwt authentication
app.get('/user', passport.authenticate('jwt', { session: false }), (req, res) => {
res.json({
user: req.user
});
});
// Request from front-end
fetch('/user', {
method: GET,
headers: {
'Authorization' : `Bearer ${localStorage.getItem('jwt')}`,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment