bradtraversy / meanauthapp

Complete MEAN stack app with authentication
242 stars 152 forks source link

JWT - now needs a plain user object #25

Closed ToMaple2 closed 6 years ago

ToMaple2 commented 6 years ago

In routes/users.js, the call to jwt.sign() now expects the user object to be a plain object instead of the one returned by User.getUserByUsername(). I'm getting:

Error: Expected "payload" to be a plain object.
    at validate (/Users/tmaple/.../node_modules/jsonwebtoken/sign.js:34:11)
    at validatePayload (/Users/tmaple/.../node_modules/jsonwebtoken/sign.js:56:10)
    at Object.module.exports [as sign] (/Users/tmaple/.../node_modules/jsonwebtoken/sign.js:108:7)
    at User.comparePassword (/Users/tmaple/.../routes/users.js:23:23)
    ...

So I added:

    const plainUserObject = {
        name: user.name,
        email: user.email,
        username: user.username,
        password: user.password
    }

and pass that into jwt.sign()

ToMaple2 commented 6 years ago

Unfortunately, this "fix" appears to have a downstream effect. When calling tokenNotExpired() in auth.service.js, it always returns false.

tomcatbuzz commented 6 years ago

The payload function it is referring to is located in Passport.js and I am attaching the working code for that. I have forked this repo and will be commiting to a pull request. Not sure if this is the fix you are looking for or if you are running tests. I am bolding changes from the original.

const JwtStrategy = require('passport-jwt').Strategy; const ExtractJwt = require('passport-jwt').ExtractJwt; const User = require('../models/user'); const config = require('../config/database');

module.exports = function(passport) { let opts = {}; opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt'); opts.secretOrKey = config.secret; passport.use(new JwtStrategy(opts, (jwt_payload, done) => { User.getUserById(jwt_payload.data._id, (err, user) => { if(err) { return done(err, false); }

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

})); }

nupurkulkarni411 commented 6 years ago

even after making changes in passport.js as mentioned by @tomcatbuzz I am getting same error

tomcatbuzz commented 6 years ago

What is the error you are getting?

xmatzx commented 6 years ago

@tomcatbuzz i also made the changes in passport.js as you mentioned and still get the same error: Error: Expected "payload" to be a plain object.

tomcatbuzz commented 6 years ago

@xmatzx Brad's github repo has been updated with the changes, so you need to follow the directions for installing and running the backend nodejs and front end Angular 5. You will also need to create a database on Mlab for when you get ready to deploy to Heroku. Just check all your code in App.js and passport, to make sure you don't have a typing error.

Rafael955 commented 6 years ago

@ToMaple2 your solution worked for me