我的登录请求得到了200的响应,但任何进一步的身份验证检查请求都会得到401的响应,因为deserializeUser从未被调用。我深入研究了Passport源代码,并注意到Passport会检查req._passport.session.user是否存在,如果不存在,它就不会调用deserializeUser。
我在Stackoverflow上搜索了其他问题,似乎我有特殊情况。
只有一种本地策略认证类型,我使用Ajax请求进行登录请求,已配置CORS设置,http://localhost:8080 - 前端,http://localhost:3000 - 后端)
我使用bodyParse、cookieParser、express session、passport initialize和passport sessions。Express session secure:false 配置为通过http运行auth请求。
您可以在这里找到我的项目(后端package.json没问题,所以您可以使用它,它没有缺少的依赖项,至于前端不确定),至少您可以在那里检查代码。
后端https://github.com/rantiev/template-api 前端https://github.com/rantiev/template-angular
Express session配置和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')));
};
护照配置在这里 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);
});
};
cookie-session
中间件代替express-session
中间件,这样设置会更少、时间更短、头痛也会更少。 - Daniel