-
-
Save vesse/453b2940065e751cfdfe to your computer and use it in GitHub Desktop.
// | |
// 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); | |
@vmehera123 were you able to solve this? I got the same problem.
me too.
@vmehera123 @ivancalva @skyvow
I ran into the same issue. If you're adding the token in the Authorization header with the Bearer approach you will need to specify the authScheme parameter as 'Bearer' in your opts object. Passport-jwt will look for 'JWT' as the scheme in the Authorization header by default.
var passport = require("passport");
var passportJWT = require("passport-jwt");
var users = require("./users.js");
var _ = require('lodash');
var cfg = require("../../config/config.js");
var ExtractJwt = passportJWT.ExtractJwt;
var Strategy = passportJWT.Strategy;
var params = {
secretOrKey: cfg.jwtSecret,
jwtFromRequest: ExtractJwt.versionOneCompatibility({authScheme: 'Bearer'})
};
module.exports = function() {
var strategy = new Strategy(params, function(payload, done) {
var user = _.find(users,{'id': payload.id});
if (user) {
return done(null, user);
} else {
return done(new Error("User not found"), null);
}
});
passport.use(strategy);
return {
initialize: function() {
return passport.initialize();
},
authenticate: function() {
return passport.authenticate("jwt", cfg.jwtSession);
}
};
};
Thank you very much for this example!
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)); })
hi! any solution with passport-jwt?
app.use("/api", passport.authenticate("jwt", {session: false}));
/login route, that create jwt
so i generate token, and in my client-side add this token to header["authorization"]
everithing ok, but when i'm trying get secure route, i'm got error 401 (not authorized)
sory for bad english, break my head with this passport strategy.