所以我正在尝试使用node.js,passport.js和angular2构建一个简单的登录/授权工具。我目前的问题是,当用户可以登录时,会话信息似乎没有传递到前端服务器,或者前端服务器也没有传回护照信息。
当登录用户似乎一直到调用res.send的部分时,此时已经调用了serialize并且已经设置了req.sessions.passport.user;但是,当用户尝试转到授权页面时,当cookie存在时,护照丢失。虽然反序列化也从未被调用,但中间件被称为/看起来被称为。当中间件到达反序列化器时,没有附加护照/用户,因此从不调用反序列化。
此时我想知道它是否可能是CORS问题或者是angular2的问题,但我已经在这方面工作了好几天,似乎是按照建议的方式进行的。我也尝试过重建它并以多种方式设置CORS以及中间件,我的想法已经用完了。我也在使用快速会话,但这似乎有效,因为我创建的cookie存在。
身份验证结束时的会话数据,但在响应站点之前 会议{ 曲奇饼: {路径:' /', _expires:null, originalMaxAge:null, httpOnly:是的, 安全:假}, 护照: {user: 匿名{ 用户名:' test', 哈希:' 4024ca40c4372e029459a1d2d52a25b2fc4642f980f6cc948cc4b35f6350adde', }}
进一步请求后的会话数据 会议{ 曲奇饼: {路径:' /', _expires:null, originalMaxAge:null, httpOnly:是的, 安全:假}}
相关守则: Passport.js
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((users, done) => {
var id=users.username;
db.one('select * from users where username = $1', id)
.then((user) => {
done(null, user);
})
.catch((err) => { done(err,null); });
});
local.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const init = require('./passport');
var promise = require('bluebird');
var options = {
// Initialization Options
promiseLib: promise
};
var hashclient = require('hashapi-lib-node');
const crypto = require('crypto');
var hash = crypto.createHash('sha256');
var pgp = require('pg-promise')(options);
var connectionString = 'postgresql://...';
var db = pgp(connectionString);
const optionsPassport = {};
init();
passport.use(new LocalStrategy(optionsPassport, (username, password, done) => {
db.one('select * from users where username = $1', username)
.then((user) => {
hash.update(password);
var encryptedPassword=hash.digest('hex');
hash = crypto.createHash('sha256');
if (!user) return done(null, false, { message: 'Incorrect username.' });
if (encryptedPassword!=user.password) {
return done(null, false, { message: 'Incorrect information.' });
} else {
return done(null, user);
}
})
.catch((err) => { return done(err); });
}));
helpers.js
function loginRequired(req, res, next) {
if (!req.user) return res.status(401).json({status: 'Please log in'});
return next();
}
Router.js示例
const users = require('express').Router();
const auth = require('./auth');
const update = require('./update');
const password = require('./password');
const authHelpers = require('./helpers');
const passport = require('./local');
users.post('/update', authHelpers.loginRequired, update);
users.get('/:userId', authHelpers.loginRequired, single);
users.post('/create', create);
users.post('/auth', passport.authenticate('local'), auth);
app.js
var passport = require('passport');
app.use(cookieParser())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({
secret: 'X+a1+TKXwd26mkiUUwqzqQ==',
resave:true,
saveUninitialized:true,
cookie:{secure:false}
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(function (req, res, next) {
var allowedOrigins = ['http://localhost:3000']
res.header('Access-Control-Allow-Origin', allowedOrigins);
res.header( 'Access-Control-Allow-Headers', 'withCredentials, Access-Control-Allow-Headers, Origin, X-Requested-With, X-AUTHENTICATION, X-IP, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Request-Headers');
res.header( 'Access-Control-Allow-Methods', 'GET, OPTIONS, HEAD, POST, PUT, DELETE');
res.header( 'Access-Control-Allow-Credentials', true);
next();
});
var routes = require('./routes');
app.use('/', routes);
前端http服务
getData (url:string, data:any): Observable<any> {
var headers = new Headers({ 'Content-Type': 'application/json', withCredentials: true });
var options = new RequestOptions({ headers: headers });
return this.http.get(url,options)
.map((res: Response): data => res.json())
.catch(this.handleError);
}
答案 0 :(得分:0)
问题出在前端我没有在正确的位置将问题设置为true
var options = new RequestOptions({ headers: headers, withCredentials: true });