我正在尝试使用passport-facebook Passport策略进行用户身份验证。当我尝试访问req.user._id
时,我收到错误
`TypeError: Cannot read property '_id' of undefined.`
我已经查看了与此相关的其他答案,这些答案似乎都围绕着会话中间件,但一切似乎都是有序的。我有一种感觉,这可能与我在端口3000上运行react-webpack-dev服务器的事实有关,该服务器代理到端口3001的快递应用程序的后端请求,但我不太确定。
routes.js:
var isAuthenticated = function (req, res, next) {
if (req.isAuthenticated()) {
console.log("LOGGED IN")
return next()
}
console.log("NOT LOGGED IN")
res.redirect('http://localhost:3001/api/auth/facebook')
}
// get logged in users' feed array, and return threads
router.get('/api/feed', isAuthenticated, function (req, res, next) {
console.log("LOGGED IN")
User.findOne({'_id': req.user._id }, function (err, user) {
Thread.find({
'_id': { $in: user.feed }
}).sort('-date').exec(function (err, threads) {
console.log(threads)
res.json(threads)
})
})
})
router.get('/api/auth/facebook',
passport.authenticate('facebook', { authType: 'rerequest' }),
router.get('/api/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect: 'http://localhost:3000',
failureRedirect: 'http://localhost:3000/signup',
session: true
}), function (req, res) {
req.session.save(function (err) {
if (err) {
console.log(err)
}
})
})
)
server.js:
var settings = require('./config')
// Express server, which handles requests on port 3001
var path = require('path')
var express = require('express')
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')
var mongoose = require('mongoose')
var passport = require('passport')
var session = require('express-session')
var app = express()
app.set('port', settings.expressPort)
app.use('/', express.static(path.join(__dirname, 'public')))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(cookieParser())
app.use(session({secret: 'secret', resave: true, saveUninitialized: true}))
app.use(passport.initialize())
app.use(passport.session())
var initPassport = require('./passport/init')
initPassport(passport)
// connect to MongoDB
mongoose.connect('mongodb://localhost/testdb', function (err, db) {
if (!err) {
console.log('Connected to Database. . .')
} else {
console.log(err)
}
})
require('./models/Thread')
require('./models/Comment')
require('./models/User')
var routes = require('./routes/index')(passport)
app.use('/', routes)
app.listen(app.get('port'), function () {
console.log('Express server started at http://localhost:' + settings.expressPort + '/')
})
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
// Hot-reloading dev-server
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
// Proxy backend requests to Express server
proxy: {
"/api/*": "http://localhost:" + settings.expressPort
}
}).listen(settings.webpackServerPort, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Webpack dev react server listening at http://localhost:' + settings.webpackServerPort + '/');
});
护照/ facebook.js:
var FaceBookStrategy = require('passport-facebook').Strategy
var mongoose = require('mongoose')
var User = mongoose.model('User')
var config = require('../config')
module.exports = function (passport) {
passport.serializeUser(function (user, done) {
done(null, user.id)
})
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user)
})
})
passport.use(new FaceBookStrategy({
clientID: config.auth.facebookAuth.clientID,
clientSecret: config.auth.facebookAuth.clientSecret,
callbackURL: config.auth.facebookAuth.callbackURL,
scope: ['public_profile', 'email', 'user_friends'],
profileFields: ['id', 'displayName', 'email', 'friends']
},
// facebook sends back token and profile
function (token, refreshToken, profile, done) {
// async
process.nextTick(function () {
User.findOne({ 'facebook.id': profile.id }, function (err, user) {
if (err)
return done(err);
if (user) {
return done(null, user)
} else {
var newUser = new User()
newUser.facebook.id = profile.id
newUser.facebook.token = token
newUser.facebook.name = profile.displayName
if (profile.emails) {
newUser.facebook.email = profile.emails[0].value
}
newUser.facebook.friends = profile._json.friends.data
newUser.save(function (err) {
if (err)
throw err
return done(null, newUser)
})
}
})
})
}
))
}
访问/api/auth/facebook
似乎正常工作。如果我退出Facebook并尝试访问/ api / feed,它会将我重定向到facebook登录页面,然后登录后,将我重定向到我的Feed页面。但是,req.user
仍未定义。
编辑:我现在在chrome控制台中看到以下错误:
XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?auth_type=rerequest&response_type=cod…back&scope=public_profile%2Cemail%2Cuser_friends&client_id=285831851754236. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.