Skip to content

Instantly share code, notes, and snippets.

@vesse
Last active October 3, 2024 10:52
Show Gist options
  • Save vesse/453b2940065e751cfdfe to your computer and use it in GitHub Desktop.
Save vesse/453b2940065e751cfdfe to your computer and use it in GitHub Desktop.
Two Passport + JWT (JSON Web Token) examples
//
// Implementation using express-jwt middle
//
var express = require('express'),
ejwt = require('express-jwt'),
jwt = require('jsonwebtoken'),
passport = require('passport'),
bodyParser = require('body-parser'),
LocalStrategy = require('passport-local').Strategy,
BearerStrategy = require('passport-http-bearer').Strategy;
var secret = 'super secret',
users = [
{id: 0, username: 'test', password: 'test'}
];
passport.use(new LocalStrategy(function(username, password, cb) {
var user = users.filter(function(u) {
return u.username === username && u.password === password
});
if (user.length === 1) {
return cb(null, user[0]);
} else {
return cb(null, false);
}
}));
var app = express();
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(ejwt({secret: secret, userProperty: 'tokenPayload'}).unless({path: ['/login']}));
// First login to receive a token
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) return next(err);
if (!user) {
return res.status(401).json({ status: 'error', code: 'unauthorized' });
} else {
return res.json({ token: jwt.sign({id: user.id}, secret) });
}
})(req, res, next);
});
// Load the user from "database" if token found
app.use(function(req, res, next) {
if (req.tokenPayload) {
req.user = users[req.tokenPayload.id];
}
if (req.user) {
return next();
} else {
return res.status(401).json({ status: 'error', code: 'unauthorized' });
}
});
// Then set that token in the headers to access routes requiring authorization:
// Authorization: Bearer <token here>
app.get('/message', function(req, res) {
return res.json({
status: 'ok',
message: 'Congratulations ' + req.user.username + '. You have a token.'
});
});
// Error handler middleware
app.use(function(err, req, res, next) {
console.error(err);
return res.status(500).json({ status: 'error', code: 'unauthorized' });
});
app.listen(3000);
//
// Implementation using HTTP Bearer strategy and jsonwebtoken
//
var express = require('express'),
jwt = require('jsonwebtoken'),
passport = require('passport'),
bodyParser = require('body-parser'),
LocalStrategy = require('passport-local').Strategy,
BearerStrategy = require('passport-http-bearer').Strategy;
var secret = 'super secret',
users = [
{id: 0, username: 'test', password: 'test'}
];
passport.use(new LocalStrategy(function(username, password, cb) {
var user = users.filter(function(u) {
return u.username === username && u.password === password
});
if (user.length === 1) {
return cb(null, user[0]);
} else {
return cb(null, false);
}
}));
passport.use(new BearerStrategy(function (token, cb) {
jwt.verify(token, secret, function(err, decoded) {
if (err) return cb(err);
var user = users[decoded.id];
return cb(null, user ? user : false);
});
}));
var app = express();
app.use(bodyParser.json());
app.use(passport.initialize());
// First login to receive a token
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) return next(err);
if (!user) {
return res.status(401).json({ status: 'error', code: 'unauthorized' });
} else {
return res.json({ token: jwt.sign({id: user.id}, secret) });
}
})(req, res, next);
});
// All routes from this point on need to authenticate with bearer:
// Authorization: Bearer <token here>
app.all('*', function(req, res, next) {
passport.authenticate('bearer', function(err, user, info) {
if (err) return next(err);
if (user) {
req.user = user;
return next();
} else {
return res.status(401).json({ status: 'error', code: 'unauthorized' });
}
})(req, res, next);
});
app.get('/message', function(req, res) {
return res.json({
status: 'ok',
message: 'Congratulations ' + req.user.username + '. You have a token.'
});
});
// Error handler middleware
app.use(function(err, req, res, next) {
console.error(err);
return res.status(500).json({ status: 'error', code: 'unauthorized' });
});
app.listen(3000);
@niorad
Copy link

niorad commented Sep 15, 2017

Thank you very much for this example!

@kerolosFawzy
Copy link

if I need to used passport.authenticate to get user data and use it to authenticate the user
I try this code
exports.verifyAdminUser = passport.authenticate('jwt', { session: false }, (done) => { console.log(done); User.findById({ _id: user._id }) .then((user) => { console.log(user); }, (err) => { return err; }); });
but sure it didn't work and done always null
I want to verify if the user is admin or not and use it like this
.get(authenticate.verifyAdminUser, (req, res, next) => { Dishes.find({}) .populate('comments.author') .then((dishes) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(dishes); }, (err) => next(err)) .catch((err) => next(err)); })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment