Sunday, 7 May 2017

passport authentication callback not calling passport middleware

I am trying to test if a GET request to a specific route is protected by using JSON Web Tokens with passport JwtStrategy; however, it seems like the passport.use middle ware function I have in my server.js file is not executing. The console.log I have in there never shows up in my shell/terminal. My login route works, but not the profile route. I am using postman and I entered http://localhost:3000/profile for the GET method and in the Headers tab I chose Authorization for Key and for the Value I copied and pasted the long JSON web token string, but it keeps saying unauthorized. That is because my passport.use function is never getting executed.

//Server.js file

var JwtStrategy = require("passport-jwt").Strategy;
var ExtractJwt = require("passport-jwt").ExtractJwt;

var User = require("../models/user");
var config = require('./secret');

app.use(passport.initialize());
app.use(passport.session());

let options = {};
//pass token back and forth
options.jwtFromRequest = ExtractJwt.fromAuthHeader();
options.secretOrKey = config;
passport.use(new JwtStrategy(options, (jwt_payload, done) => {
  *******************************************
  //this console log doesn't show up in shell which makes be believe its never getting here
  *******************************************
  console.log("JWT PAYLOAD", jwt_payload)
  User.getUserById(jwt_payload._id, (err, user) => {
    if(err){
      return done(err, false);
    }

    if(user){ //null for error
      return done(null, user);
    }else{
      return done(null, false);
    }
  });
}));

//Routes file where the passport.authenticate callback is called

var passport = require('passport');
var jwt = require('jsonwebtoken');
var secret = require('../config/secret')

var User = require('../models/user');

router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res) => {
    res.json({user: req.user});
});



via henhen

No comments:

Post a Comment