简体   繁体   English

req.user未定义

[英]req.user is undefined

I want to write a REST-API with NodeJS+Restify and PassportJS for the authentication. 我想使用NodeJS + Restify和PassportJS编写REST-API进行身份验证。 When the user logs in, I generate a sessionId and store it in a session, which I create myself. 当用户登录时,我会生成一个sessionId并将其存储在我自己创建的会话中。

var Passport                = require( 'passport' );
var PassportBearerStrategy  = require('passport-http-bearer').Strategy;
// Authentication
Passport.use( new PassportBearerStrategy( function( sessionId, cb ) {
    Auth.getSession( sessionId, function( userId ){
        cb( ( !!userId ), { userId: userId }, userId );
    });
}));

server.get(
    '/user',
    Passport.authenticate( 'bearer' ),
    function( req, res, next ){
        console.info( req.user  ); // undefined
        respond( res, {} );
        return next();
    }
);

Everything works except, that in the function bellow, req.user is undefined . 除了在下面的函数中, req.userundefined之外,其他所有方法都可以正常工作。 I read, that you have to enable session. 我读到,您必须启用会话。 But I already implemented my own session, I do not need another one. 但是我已经实现了自己的会话,不需要另一会话。
All I need is that, if I say cb( true, user ) it arrives in the function below. 我需要的是,如果我说cb( true, user )它将到达下面的函数中。

Is there any way to solve this? 有什么办法解决这个问题?

As I get from the code in this example the callback cb follows the standard node format, so gets an error as first argument and the user as second. 正如我从本例中的代码中获得的那样,回调cb遵循标准节点格式,因此将错误作为第一个参数,将用户作为第二个参数。 I think that callback is what set req.user and manage all post-auth boilerplate. 我认为回调是设置req.user并管理所有验证后样板的东西。 You should try to call it as `cb(null, user) 您应该尝试将其称为`cb(null,user)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM