0

I want to write a REST-API with NodeJS+Restify and PassportJS for the authentication. When the user logs in, I generate a sessionId and store it in a session, which I create myself.

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. 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.

Is there any way to solve this?

Rob
  • 14,746
  • 28
  • 47
  • 65
TSM
  • 189
  • 2
  • 9
  • 1
    I have never used that strategy, only local-strategy. On local, you need to have a function to serialize and to deserialize the user. It's the desarialize function which gives you the user that will later be accesible through req.user. Aren't you missing this function? – yBrodsky Sep 14 '17 at 12:21
  • @yBrodsky, You are right, these functions are missing. I added them exactly like described here: https://stackoverflow.com/questions/27637609/understanding-passport-serialize-deserialize But req.user is still undefined. – TSM Sep 14 '17 at 12:33

1 Answers1

1

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. I think that callback is what set req.user and manage all post-auth boilerplate. You should try to call it as `cb(null, user)

ilmirons
  • 624
  • 6
  • 16