tonejac tonejac -4 years ago 219
Node.js Question

Passport.js http-bearer Strategy, get req to pass through to function

I'm using the HTTP Bearer Strategy

Here's my Bearer Strategy Code:

var passport = require('passport'),
url = require('url'),
BearerStrategy = require('passport-http-bearer').Strategy,
config = require('../config'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
users = require('../../app/controllers/users.server.controller');

module.exports = function() {
// Use bearer strategy
passport.use(new BearerStrategy(
function(token, done) {

User.findOne({ token: token }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
return done(null, user, { scope: 'all' });

Instead of handling the route function in my routes file (like in their example) I'm using my user.server.controller.js with an exports function like so:

// route

// export function in user controller
exports.bearerSignin = function(req, res) {
console.log('bearerSignin', req.user); // CAN DETECT req.user HERE FINE
passport.authenticate('bearer', {session:false}, function(req, res) {
console.log('inside authenticate', req.user); // BUT HERE IT'S SHOWING UP null
var response = {
userObj: req.user,
redirectUrl: req.session.redirectUrl
})(req, res);

How do I properly construct my exports.bearerSignin function to handle the req and authenticate with Passport?

BTW, here is the JSON for the user object being passed to the exports function:

_id: abc123idnumber,
photo: '',
provider: 'local',
username: 'userabc123',
__v: 0,
created: Tue Aug 23 2016 00:52:20 GMT+0000 (UTC),
updated: Fri Aug 26 2016 03:53:17 GMT+0000 (UTC),
freeEventsCount: 1,
eventsSubscription: false,
profiles: [],
roles: [ 'user' ],
google: {},
facebook: {},
{ profilePhoto: '',
name: 'Joe Smith',
token: 'tokenabc123',
username: 'tonejac',
id: 'abc123' },
localAccountExists: true,
firstName: 'joe',
email: ''

Answer Source

Your callback is in the wrong place (it's in passport.authenticate instead of the returned middleware).

exports.bearerSignin = function(req, res) {
    passport.authenticate('bearer', {
        session: false
    })(req, res, function() { // this is the function called after auth
        console.log('inside authenticate', req.user);
        var response = {
            userObj: req.user,
            redirectUrl: req.session.redirectUrl
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download