我正在使用passportjs进行用户身份验证。
通过使用邮递员,我可以成功登录并且req.isAuthenticated在登录后始终在子序列请求中返回true。
通过使用角度$ http,但登录工作正常,但req.isAuthenticated总是在子序列请求中返回false。我的角应用(localhost:3000)和节点应用(heroku)是在不同的域。我的想法是它可能与CORS或会话cookie有关,因为我没有在浏览器中看到任何cookie。
我做了什么
- 我试图设置请求头允许CORS。
- 我也尝试设置访问控制允许证书在$ http和节点应用程序的角度。
不幸的是,所有的尝试都失败了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'](https://docs.angularjs.org/api/ng/service/$http)配置选项。 – robertklep
@robertklep I在我的角码中包含此选项。看看我的角色部分$ http.get('xxxx',{withCredentials:true})。成功..... – eded
对不起,错过了:-( – robertklep