在提取用户上使用Passport-jwt时,req.user是未定义的

时间:2019-08-01 14:14:19

标签: javascript node.js express passport-jwt

我已经在Stackoverflow上检查了多个答案,并且还在文档中进行了检查,但仍然无法弄清我的问题。当我尝试登录并注册时,它可以正常运行,我有我的令牌。只是获取我的current_user get('/ isAuth')我不确定的噩梦!!!

const Authentication = require("../controllers/authentication");
const passport = require("passport");

const requireAuth = passport.authenticate('jwt', {session: false});
const requireSignin = passport.authenticate('local', {session: false});

module.exports = app => {
   app.post('/signup', Authentication.signup);
   app.post('/signin', requireSignin, Authentication.signin);

  //  Current User is undefined !!!!!
  app.get('/isAuth', Authentication.fetchUser);

我的password.js

const keys = require("../config/keys");
const passport = require("passport");
const User = require("../models/User");
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const localStrategy = require("passport-local");

// Create local strategy
const localOptions = { usernameField: "email" };
const localLogin = new localStrategy(localOptions, function(email,password,done) {
  // verify this username and password, call done with the user
  // if it is the correct username and password
  // otherwise, call done with false
  User.findOne({ email: email }, function(err, user) {
    if (err) {return done(err);}
    if (!user) {return done(null, false);}
    // compare passwords - is password is equal to user.password?
    user.comparePassword(password, function(err, isMatch) {
      if (err) {return done(err);}
      if (!isMatch) {return done(null, false);}
      return done(null, user);
    });
  });
});

// setup option for jwt Strategy
const jwtOptions = {
  jwtFromRequest: ExtractJwt.fromHeader('authorization'),
  secretOrKey: keys.secret
};

// Create Jwt strategy
const jwtLogin = new JwtStrategy(jwtOptions, function(payload, done) {
  // See if the user Id in the payload exists in our database
  // If does, call 'done' with that other
  // otherwise, call done without a user object
  User.findById(payload.sub, function(err, user) {
    if (err) {return done(err, false);}
    if (user) {
      done(null, user);
    } else {
      done(null, false);
    }
  });
});

// Tell passport to use this strategy
passport.use(jwtLogin);
passport.use(localLogin);

// Generate token
passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id).then(user => {
    done(null, user);
  });
});

./ controller / authentication.js

const User = require('../models/User');
const jwt = require('jwt-simple');
const config = require('../config/keys');

function tokenForUser(user){
    const timestamp = new Date().getTime();
    return jwt.encode({sub: user.id, iat: timestamp}, config.secret);
}
exports.signup = function(req,res,next){
    console.log(req.body)
    const email = req.body.email;
    const password = req.body.password;

    if(!email || !password){
        return res.status(422).send({error: 'You must provide email and password'});
    }
    // See if user with the given email exists
    User.findOne({email: email}, function(error, existingUser){
        if (error){return next(error)};
        // if a user with email does exist, return an error
        if (existingUser){
            return res.status(422).send({error: 'Email is in use'});
        }
        // if a user with email does not exist, create and save record
        const user = new User({
            email: email,
            password: password
        });

        user.save(function(error){
            if (error){return next(error);}
            // respond to request indicating the user was created
            res.json({token: tokenForUser(user)});
        })
    })
}

exports.signin = function (req,res,next){
    // user has already had their email and password auth
    // we just need to give them a token
    res.send({token: tokenForUser(req.user)});
}

// here is my problem...
exports.fetchUser = function (req, res, next) {
    console.log('this is ',req.user)
  };

仍然停留了很多天……这是一场噩梦!!!如果有人有解决方案。

登录后,如果我想去我的路线/ isAuth来检查我的用户数据: enter image description here

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用对req对象调用isAuthenticated函数的中间件?此功能由passport添加,通常是检查请求是否已通过验证的推荐方法。

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }

  res.redirect("/");
}

然后,当用户点击您的isAuth路线时,您可以调用此函数:

app.get('/isAuth', isLoggedIn, Authentication.fetchUser);