Last active
April 27, 2019 14:34
-
-
Save gtalin/b1b449334a718c54d7d77c8d32d6e755 to your computer and use it in GitHub Desktop.
json web token authentication using passport
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 passport = require('passport'); | |
const JwtStrategy = require('passport-jwt').Strategy; | |
const ExtractJwt = require('passport-jwt').ExtractJwt; | |
const mongoose = require('mongoose'); | |
const User = mongoose.model('users'); | |
const jwtOptions = { | |
jwtFromRequest: ExtractJwt.fromHeader('Authorization'), | |
secretOrKey: process.env.SECRET_KEY | |
}; | |
console.log("jwtOptions", jwtOptions); | |
const jwtLogin = new JwtStrategy(jwtOptions, function(payload, done) { | |
// If id in payload exists in DB | |
// call done with that user | |
// if not, call done without a userobject | |
console.log("The payload is:: ",jwtOptions, payload); | |
debugger; | |
User.findById(payload) | |
.then((user) => { | |
console.log(`User is ${user}`); | |
// if (err) return done(err, false); | |
if (!user) | |
return done(null, false); | |
return done(null, user); | |
}) | |
.catch((err) => { | |
console.log(`Error is ${err}`); | |
done(err, false); | |
}) | |
}); | |
// Tell passport to use this strategy | |
passport.use(jwtLogin); |
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 passport = require('passport'); | |
require('./services/passport'); | |
const requireAuth = passport.authenticate('jwt', { session: false }); | |
module.exports = (app) => { | |
app.route('/') | |
.get(function(req, res) { | |
res.json({msg:'hello'}); | |
}); | |
app.route('/protected') | |
.get(function(req, res, next) { | |
debugger; | |
next(); | |
}, requireAuth, function(req, res) { | |
res.json({ msg: 'Protected roue'}); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment