【发布时间】:2015-09-28 21:13:10
【问题描述】:
我正在使用 passportjs 进行用户身份验证。
通过使用邮递员,我可以成功登录,并且 req.isAuthenticated 总是在登录后的子序列请求中返回 true。
通过使用角度 $http,但是,登录工作正常,但 req.isAuthenticated 总是在子序列请求中返回 false。我的 angular app(localhost:3000) 和 node app(heroku) 位于不同的域。我的想法是它可能与 CORS 或会话 cookie 有关,因为我在浏览器中看不到任何 cookie。
我做了什么
- 我尝试将请求标头设置为允许 CORS。
- 我还尝试在角度 $http 和节点应用程序中设置 Access-Control-Allow-Credentials。
很遗憾,所有尝试都失败了T_T
Nodejs 设置
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
if ('OPTIONS' == req.method) {
res.send(200);
} else {
next();
}
});
passport.serializeUser(function(account, done) {
done(null, account.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
Account.findById(id, function(err, account) {
done(err, account);
});
});
passport.use('local-signup', new LocalStrategy({
usernameField: 'email'
}, function(email, password, done) {
....
}));
passport.use('local-login', new LocalStrategy({
usernameField: 'email'
}, function(email, password, done) {
....
}));
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser(config.app.sessionSecret));
app.use(session({
secret: config.app.sessionSecret,
resave: false,
saveUninitialized: true,
cookie: { httpOnly: true, maxAge: 2419200000 }
}));
// Passport for account authentication
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
///////////////////////////////////////////////////////////////////route controller function
authenticate: function(req, res) {
if (!req.isAuthenticated()) {
res.redirect('/login');
} else {
res.status(200).send('successful');
}
}
角度
$http.post('http://xxxxx/login',
{ email: $scope.user.email,
password: $scope.user.password
})
.then(function(response) {
...
}, function(response) {
...
});
$http.get('http://xxxxx/authenticate',
{ withCredentials: true }).success(function() {
...
})
.error(function() {
... // always get here with 302 redirect
});
我的问题/我不明白的事情
- 是不是因为浏览器中没有设置会话cookie导致的问题
- 如果它与 CORS 相关,我是否遗漏了任何设置?
- 还有什么????
【问题讨论】:
-
查看
withCredentials配置选项。 -
@robertklep 我在我的角度代码中包含了这个选项。看看我的角度部分 $http.get('xxxx', {withCredentials: true}).success.....
-
对不起,错过了:-(
标签: node.js angularjs passport.js session-cookies