mikenicholson/passport-jwt

Login and Registration works but Profile still gets 401 Unauthorized

andreashp96 opened this issue · 2 comments

I have a difficulty on authentication.
User login and registration work perfectly, but not for the authentication.

Here's the passport.js:

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../model/User');
const key = require('./keys');

module.exports = (passport) => {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
opts.secretOrKey = key.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);
return done(null, false);
})
}
)
);
}

and here's the users.js:
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const User = require('../../model/User');
const key = require('../../config/keys').secret;

/**

  • @route POST api/users/register

  • @desc Register the user

  • @access Public
    */
    router.post('/register', (req, res) => {
    let {
    name,
    username,
    email,
    password,
    address,
    birthday,
    confirm_password
    } = req.body
    if(password !== confirm_password) {
    return res.status(400).json({
    msg: "Password do not match"
    });
    }

    //check username
    User.findOne({
    username: username
    }).then(user => {
    if(user){
    return res.status(400).json({
    msg: "Username is already taken"
    });
    }
    });
    //check email
    User.findOne({
    email:email
    }).then(user => {
    if(user){
    return res.status(400).json({
    msg: "Email is already registered"
    });
    }
    });

    //data is valid create new user
    let newUser = new User({
    name,
    username,
    password,
    email,
    address,
    birthday
    });

    //hash password
    bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(newUser.password, salt, (err, hash) => {
    if(err) throw err;
    newUser.password = hash;
    newUser.save().then(user => {
    return res.status(201).json({
    success: true,
    msg: "User is registered"
    });
    });
    });
    });

});

/**

  • @route POST /users/login
  • @desc Login the user
  • @access Public
    */
    router.post('/login', (req, res) => {
    User.findOne({
    username: req.body.username
    }).then(user => {
    //check if user exists
    if(!user) {
    return res.status(404).json({
    msg: "Username not found",
    success: false
    });
    }
    //user exists then check password
    bcrypt.compare(req.body.password, user.password).then(isMatch => {
    if(isMatch) {
    //password is correct then send json token to user
    const payload = {
    _id: user.id,
    username: user.username,
    name: user.name,
    email: user.email,
    address: user.address
    }
    jwt.sign(payload, key, {
    expiresIn: 604800
    }, (err, token) =>{
    res.status(200).json({
    user: user,
    success: true,
    token: Bearer ${token},
    msg: "You are logged in"
    })
    })
    } else {
    //incorrect password
    return res.status(404).json({
    msg: "Incorrect Password",
    success: false
    });
    }
    })
    })
    });

/**

  • @route POST api/users/profile
  • @desc Return the User's data
  • @access Private
    */
    router.get('/profile', passport.authenticate('jwt', {
    session:false
    }), (req, res) => {
    return res.json({
    user: req.user
    });
    });

module.exports = router;

Any idea why it's 401 unauthorized? Thank you!

Unfortunately, I'm not able to troubleshoot other peoples code. If you discover a reproducible issue with this module please open an issue with a unit test, succinct code snippet or detailed instructions to reproduce.

Consider asking a question on stack overflow. Best of luck.

@andreashp96 , did you find the solution?