我正在使用HTTP Bearer Strategy
这是我的持票人战略代码:
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' });
});
}
));
};
我没有在我的路线文件中处理路线功能(就像在他们的例子中一样),而是使用我的user.server.controller.js和一个像这样的导出函数:
// route
app.route('/auth/bearersignin').post(users.bearerSignin);
// 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
};
res.json(response);
})(req, res);
};
如何正确构建我的exports.bearerSignin函数来处理req并使用Passport进行身份验证?
BTW,这是传递给exports函数的用户对象的JSON:
{
_id: abc123idnumber,
photo: 'https://pbs.twimg.com/profile_images/abc123/IMG_2899-square_normal.jpg',
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: {},
twitter:
{ profilePhoto: 'https://pbs.twimg.com/profile_images/idabc123/square_normal.jpg',
name: 'Joe Smith',
token: 'tokenabc123',
username: 'tonejac',
id: 'abc123' },
localAccountExists: true,
firstName: 'joe',
email: 'user@example.com'
}
答案 0 :(得分:2)
您的回调位置错误(它位于passport.authenticate
而不是返回的中间件)。
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
};
res.json(response);
});
};