我的登录请求有200个响应,但是对于任何进一步的auth检查请求都有401,因为deserializeUser从未调用过。我潜入护照来源并注意到护照检查req._passport.session.user是否存在,如果不存在则不会调用deserializeUser。
我在stackoverflow上搜索了其他问题,看来我有具体的案例。
有单一的本地策略auth类型,我使用Ajax请求发出登录请求,配置CORS设置,http://localhost:8080 - 前端,http://localhost:3000后端)
我使用bodyParse,cookieParser,快速会话,护照初始化和护照会话。 Express session secure:false配置为我通过http运行身份验证请求。
你可以在这里找到我的项目(backend package.json很好用,所以你可以使用它,它没有遗漏的依赖关系,因为前端不确定),至少你可以检查那里的代码。
后端https://github.com/rantiev/template-api 前端https://github.com/rantiev/template-angular
快速会话配置和CORS在https://github.com/rantiev/template-api/blob/master/modules/appConfigure.js
var path = require('path');
var bodyParser = require('body-parser');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var MongoStore = require('connect-mongo')(session);
module.exports = function (app, express, config, mongoose) {
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, X-AUTHENTICATION, X-IP, Content-Type, Origin, Accept, Cookie');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
/*app.use(function (req, res, next) {
console.log('coockie is:', req.cookies);
});*/
app.use(session({
saveUninitialized: false,
resave: false,
secret: config.sessionsSecretToken,
cookie: {
secure: false
},
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(express.static(path.join(__dirname, '..' , 'public')));
};
Passport配置在这里https://github.com/rantiev/template-api/blob/master/api/authentication/authenticationR.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var rememberMe = require('../../modules/rememberMe');
var createAccessToken = require('../../modules/createAccessToken');
var bcrypt = require('bcrypt-nodejs');
var UserM = require('../users/userM');
module.exports = function (app, mainRouter, role) {
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
}, function (username, password, done) {
UserM.findOneQ({email: username})
.then(function(user){
if (user && bcrypt.compareSync(password, user.password)) {
done(null, user);
} else {
done(null, false);
}
})
.catch(function(err){
done(err);
});
}));
passport.serializeUser(function (user, done) {
console.log('serialize');
if (user) {
createAccessToken(user, done);
} else {
done(null, false);
}
});
passport.deserializeUser(function (token, done) {
console.log('deserialize');
UserM.findOneQ({accessToken: token})
.then(function(user){
if (user) {
done(null, user);
} else {
done(null, false);
}
})
.catch(function(err){
done(err);
});
});
app.use(passport.initialize());
app.use(passport.session());
mainRouter.post('/me', passport.authenticate('local'), function (req, res) {
res.status(200).send();
});
mainRouter.get('/logout', function (req, res) {
req.logout();
res.redirect('/');
});
mainRouter.get('/me', function (req, res) {
if (!req.user) {
res.status(401).send('Please Login!');
return;
}
var currentUser = {
id: req.user._id,
role: req.user.role
};
res.status(200).json(currentUser);
});
};
答案 0 :(得分:2)
如果查看调用堆栈并发现由于deserializeUser
未设置而未调用req._passport.session.user
,则问题如下。有问题的行在express-session
模块中:
if (!req.sessionID) {
debug('no SID sent, generating session');
generate();
next();
return;
}
如果设置了sessionID,则永远不会调用generate
:
store.generate = function(req){
req.sessionID = generateId(req);
req.session = new Session(req); // THIS
req.session.cookie = new Cookie(cookieOptions);
if (cookieOptions.secure === 'auto') {
req.session.cookie.secure = issecure(req, trustProxy);
}
};
但是可以设置req.sessionID
,而req.session
为空,这说明req._passport.session.user
为空 - req.session
永远不会设置。
我继续追溯到设置req.sessionID
时的情况,有时会使用新的Cookie设置,有时不设置。
为什么呢?我不知道,并希望有人进一步调查,但是,基本上,课程是尝试使用cookie-session
模块。
答案 1 :(得分:1)
您是否尝试过maxAge
?
app.use(express.session({ store: sessionStore,
cookie: { maxAge : 3600000 } //1 Hour
}));