0

I am trying to debug a failing JWT auth setup, which always returns a 401.

My passport setup (middleware/auth.js)

import passport from 'passport'
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt'

module.exports = function() {
  var options = {};
  options.jwtFromRequest = ExtractJwt.fromAuthHeader()
  options.secretOrKey = 'superdupersecret'

  var strategy = new JwtStrategy(options, function(payload, done) {
    console.log('this is not printing')              <---------------
    var user = payload.sub || null;
    if (user) {
      return done(null, { id: user._id });
    } else {
      return done(new Error("User not found"), null);
    }
  });

  passport.use(strategy);

  return {
    initialize: () => {
      console.log('this only prints on boot');       <---------------
      return passport.initialize();
    },
    authenticate: () => {
      console.log('this too')                        <---------------
      return passport.authenticate("jwt", {session: false});
    }
  };
};

My server.js file where I initialize passport:

import express from 'express'
(...)
var auth = require("./middleware/auth.js")();


// Instantiate app
const app = express();

// Initialize passport for auth use
app.use(auth.initialize())

And my protected route that always returns a 401:

import express from 'express'
var auth = require("../middleware/auth.js")();

const userRouter = express.Router()

userRouter.get('/dashboard', auth.authenticate(), (req, res) => {
    res.send('It worked! User id is: ' + req.user + '.')
})

export default userRouter

I have tried to add print statements within the actual passport.js module itself, as well as passport-jwt, with no success.

After the authentication middleware on the protected route, nothing logs.

I have tried a ton of setup permutations over the past 3 days now. Any help would be greatly appreciated

Community
  • 1
  • 1
softcode
  • 4,358
  • 12
  • 41
  • 68

1 Answers1

1

Ok, I followed the tutorial you mentioned and it seems to work. Here are some notes (some may be obvious, no offense).

  • Copy exactly the code as the tutorial
  • After you have everything, you need to "login". Make a POST request to /token. Content type has to be application/json and on the body of the request you need to sent an object with email and password (from tutorial).
  • After you login, the server returns a token.
  • Take that token and now make a GET request to /user. In the headers of the request add: Authorization: JWT [your token here]. You have to write "JWT" and the token separated by one space.
  • The server returns a status 200. I modified so it returns the user.

    app.get("/user", auth.authenticate(), function(req, res) { res.json({user: req.user}); });

yBrodsky
  • 4,981
  • 3
  • 20
  • 31
  • Thanks for the help @yBrodsky. It turns out that when I attach the JWT to the auth header, it must be preprended with `'JWT '` string. That fixed everything. – softcode Feb 16 '17 at 20:17
  • Yes. I have an app of my own that uses JWT and I did it myself, without using passport. Passport is not doing much in this scenario, so doing it yourself gives you the possibility of adding some flexibility (like retrieving the token with different headers, via a param or in the body. – yBrodsky Feb 16 '17 at 20:20
  • I agree. However I will be implementing various auth strategies, so consolidating them into a comprehensive package makes sense I guess. – softcode Feb 16 '17 at 20:22
  • I also have another question which has been bugging me, which is imo much simpler, if you can help http://stackoverflow.com/questions/42283841/dotenv-not-loading-properly – softcode Feb 16 '17 at 20:22