Node + Express + Passport + Mongoose:req.user 未定义

Posted

技术标签:

【中文标题】Node + Express + Passport + Mongoose:req.user 未定义【英文标题】:Node + Express + Passport + Mongoose: req.user Undefined 【发布时间】:2018-03-28 19:35:51 【问题描述】:

登录时,req.user 已定义,但在其他路径上,req.user 未定义。也许我做错了什么,我没有想法。

也从来不叫去杀灭

server.js:

var LocalStrategy = require('passport-local').Strategy;

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

const app = express();

mongoose.Promise = global.Promise;

const mongoDB = 'mongodb://mlab.com:21494/tester';
mongoose.connect(mongoDB,  useMongoClient: true )
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

app.use(function (req, res, next) 
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization');

  if ('OPTIONS' == req.method) 
    res.sendStatus(200);
   else 
    next();
  
);

app.use(logger('dev'));

app.use(compression());

//////////////////////////////////////////////////


passport.use(new LocalStrategy(
  function(username, password, done) 
    console.log('Strategy>>>>');
    User.findOne( username: username , function (err, user) 
      if (err)  return done(err); 
      if (!user)  return done(null, false); 
      if (!user.verifyPassword(password))  return done(null, false); 
      return done(null, user);
    );
  
));

passport.use(User.createStrategy());


passport.serializeUser(function (user, done) 
  console.log('SERIALIZE', user);   //called                     
  done(null, user.id);
);

passport.deserializeUser(function (id, done) 
  console.log('DESIRIALIZE'); // not called
  User.findById(id, function (err, user) 
    console.log('USER Desirialise', user);
    done(err, user);
  );
);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded( extended: false ));
app.use(cookieParser());
// Session
app.use(require('express-session')(
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false
));

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



//=====================LOGIN==================================
app.use('/', require('./routes/userRouters'));

userRouters.js:

const router = require('express').Router();
const jwt = require('jsonwebtoken');
const passport = require('passport');

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

router.post('/signin', passport.authenticate('local'), function (req, res, next) 
  console.log('SIGN IN');
  const  user  = req
  const token = jwt.sign( username: user.username, email: user.email, _id: user._id , 'RESTFULAPIs')
  console.log('REQ USER>>', req.user); // defined
  console.log('SESION', req.session.cookie); // passport defined
  res.json(
    user: 
      user: user.username,
      email: user.email,
      created: user.created
    ,
    token: token
  );
)

router.get('/test', function (req, res) 
console.log('============================================');
  console.log('reqUSER', req.user); //undefined
  console.log('SESION', req.session.cookie); // passport undefined 
  res.json(req.user); 
);
///////////////////////////////////////////////////
router.post('/register', function (req, res, next) 
  const  username, email, password  = req.body;

  User.register(
    new User( username, email, password ),
    req.body.password,
    (err, account) => 
      if (err) 
        res.send(
          status: 400,
          error: err.message,
          data: 
            errorName: err.name
          
        );

        return;
      

      passport.authenticate('local')(req, res, function () 
        console.log('REG req.user:>>>>', req.user); // defined
        res.send( auth: true )
      );
    );
)

router.get('/logout', function (req, res) 
  console.log('============================================');
  console.log('reqUSER', req.user); //undefined
  console.log('SESION', req.session.cookie); // passport undefined
  req.logout();
  res.json( messageSuccessful: 'Logout successful' );
  consol.log(req.user)// null
);

客户:

 signUp(user) 
    const  cookies  = this.props;
    const date = new Date();
    date.setDate(date.getDate() + 2000)

    axios.post(`$URL/register`, user).then((result) => 
      console.log('RESULT SIGNIN', result);

      if (result.data.error) 
        this.setState( error: result.data.error )
       
        this.setState(
          message: result.data.message,
          auth: result.data.auth
        )
      
    
    )
  

  signIn(user) 
    const  cookies  = this.props;
    const date = new Date();
    date.setDate(date.getDate() + 2000);
    axios.post(`$URL/signin`, user).then((result) => 
      console.log('RESULT SIGNIN', result);
      if (result.data.error) 
        this.setState( loginErrorMessage: result.data.error )
       
        this.setState(
          loginErrorMessage: '',
          modalIsOpen: false,
          auth: true
        )
      
    
    )
  ;

请帮助,我尝试更改会话设置,但没有帮助。 我试图修复一个多星期。

附:通过邮递员检查,一切正常,调用deserializeUser并定义req.user

【问题讨论】:

您是否使用任何数据解析器来处理发布请求? @Sagar 不,你到底在说什么,可能我没听懂问题 我将代码复制到一个节点骨架项目中,这一切似乎都有效。反序列化被调用。 (我删除了 passport.use(User.createStrategy()); 和压缩,因为我不需要它们)。你是如何测试你的api的?如果您使用的是 CURL 等工具,您是否确保将登录期间创建的 cookie 与其他请求一起传回? 登录时会创建cookies,但在以下路径中,cookies为空登录路径:Session cookie: path: '/', _expires: null, originalMaxAge: null, httpOnly: true , passport: user: '59e4a360cc73044b4a3999be' 其他路径:Session cookie: path: '/', _expires: null, originalMaxAge: null, httpOnly: true 通过邮递员检查,一切正常,deserializeUser 由 req.user 调用和定义。但是客户端不行 【参考方案1】:

问题出在 cors 的客户端上。我希望这对某人有所帮助。

不起作用:

axios.post(`$URL/signin`, user).then((result) => 
//something
)

工作:

const myInit = 
      method: 'post',
      headers: 
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      ,
      body: JSON.stringify(user),
      mode: 'cors',
      credentials: "include",
    ;

    fetch(`$URL/signin`, myInit).then(res => res.json())
      .then(res => 
        console.log(res)
      );

【讨论】:

以上是关于Node + Express + Passport + Mongoose:req.user 未定义的主要内容,如果未能解决你的问题,请参考以下文章

Express Passport (node.js) 错误处理

Node/Express 的 Passport 身份验证中间件 - 如何保护所有路由

Node、Express、Oauth2 和 Passport 的 Angularjs CORS 问题

如何读取通过服务器端 (node-express) 上的 Passport 设置的客户端 (react) cookie?

使用 passport.js 和 express.js (node.js) 制作安全的 oauth API

Angular 问题和“没有 'Access-Control-Allow-Origin' 标头” - 使用 OAuth 2、Passport、Express 和 Node