gpt4 book ai didi

node.js - req.session.passport 为空,未调用 deserializeUser - ExpressJS,Passport

转载 作者:IT老高 更新时间:2023-10-28 23:08:09 28 4
gpt4 key购买 nike

我在 Passport/ExpressJS 中使用 session 时遇到问题。

当我登录 req.session 时,我可以看到 Passport 是 {}:

{ cookie: 
{ path: '/',
_expires: Mon Sep 29 2014 19:37:16 GMT-0300 (BRT),
originalMaxAge: 3594522,
httpOnly: true,
secure: true },
passport: {} }

另外,我正在使用 Facebook 进行身份验证,并且没有调用 passport.deserializeUser。这是我的代码:

    passport.use(new FacebookStrategy({

// pull in our app id and secret from our auth.js file
clientID : configAuth.facebookAuth.clientID,
clientSecret : configAuth.facebookAuth.clientSecret,
callbackURL : configAuth.facebookAuth.callbackURL

},

// facebook will send back the token and profile
function(token, refreshToken, profile, done) {

// asynchronous
process.nextTick(function() {

console.log("profile " + profile.id);
console.log("profile.name "+profile.name.givenName)

// find the user in the database based on their facebook id
User.findOne({ 'facebook.id' : profile.id }, function(err, user) {

// if there is an error, stop everything and return that
// ie an error connecting to the database
if (err)
return done(err);

// if the user is found, then log them in
if (user) {
//returning undefined
//console.log(user.name + " " + user.email);
return done(null, user); // user found, return that user
} else {
// if there is no user found with that facebook id, create them
var newUser = new User();

// set all of the facebook information in our user model
newUser.facebook.id = profile.id; // set the users facebook id
newUser.facebook.token = token; // we will save the token that facebook provides to the user
newUser.facebook.name = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned
newUser.facebook.email = profile.emails[0].value; // facebook can return multiple emails so we'll take the first

// save our user to the database
newUser.save(function(err) {
if (err)
throw err;

// if successful, return the new user
return done(null, newUser);
});
}

});
});

}));

// used to serialize the user for the session
passport.serializeUser(function(user, done) {
console.log("serialize");
done(null, user.id);
});

// used to deserialize the user
passport.deserializeUser(function(id, done) {
console.log("deserialize");
User.findById(id, function(err, user) {
console.log(user);
done(err, user);
});
});

我尝试将这两种方法移到开头,但没有任何区别。 passport.serializeUser 调用就好了。

这是我初始化passport的地方:

app.use (cookieParser());
app.use(session({ secret: 'appsecret', saveUninitialized: true, cookie: { secure: true, maxAge: new Date(Date.now() + 3600000) }, key:'connect.sid' }));

app.use(passport.initialize());
app.use(passport.session());

这是我的路线:

// =====================================
// FACEBOOK ROUTES =====================
// =====================================
// route for facebook authentication and login

app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));

// handle the callback after facebook has authenticated the user
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect : '/home',
failureRedirect : '/login'
}));

有人可以帮我解决这个问题吗?

谢谢!

最佳答案

背景

对我来说,没有调用 deserializeUser 和空 Passport 对象的问题是跨域问题。当我从 localhost:4200 向 localhost:1000 发送 ajax 请求时,cookie 和 session 对我的 Ember.js 客户端不起作用。但是, postman 分机收到了正确的响应。 Passport 对象也正确填写了数据。 User.deserializeUser 被正确调用。

解决方案

为了解决这个问题,我必须设置正确的服务器端和客户端 HTTP header 。服务器端(node.js + express + passport):

# The important part. Must go AFTER the express session is initialized
app.use passport.initialize()
app.use passport.session()

# Enable CORS
# X-Requested-With, X-AUTHENTICATION, X-IP
# https://stackoverflow.com/a/18290875/2166409
app.use (req, res, next) ->
res.header 'Access-Control-Allow-Origin', 'http://localhost:4200'
res.header 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, X-AUTHENTICATION, X-IP, Content-Type, Accept'
res.header 'Access-Control-Allow-Credentials', true
res.header 'Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'
next()

app.use '/api/v1', router

客户端:

如果使用 jQuery,请将其添加到 $.ajax 选项中:

xhrFields: { withCredentials:true }

然后一切都按预期工作:

DESERIALIZE USER
{ id: '547fabf22a098ade53e6e48e',
name: 'test',
firstName: 'test',
email: 'test@wp.pl' }
LOGIN SUCCESS SESSION
{ cookie:
{ path: '/',
_expires: Thu Dec 04 2014 20:26:52 GMT+0100 (CET),
originalMaxAge: 3597205,
httpOnly: false },
passport:
{ user:
{ id: '547fabf22a098ade53e6e48e',
name: 'test',
firstName: 'test',
email: 'test@wp.pl' } } }

这些答案帮助了我:about Ember.js , jQuery.ajax .

关于node.js - req.session.passport 为空,未调用 deserializeUser - ExpressJS,Passport,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26109556/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com