当使用angular度$ http请求时,护照req.isAuthenticated始终返回false

我正在使用passportjs进行用户身份validation。

通过使用邮递员 ,我可以成功login和req.isAuthenticated总是返回我在login后的子序列请求为true。

通过使用angular$ http ,但是,login工作正常,但req.isAuthenticated总是在子序列请求中返回false。 我的angular度应用程序(localhost:3000)节点应用程序(heroku)在不同的域。 我的想法是,它可能涉及CORS或会话cookie,因为我没有看到我的浏览器中的任何cookie。

我做了什么

  1. 我试图设置请求头允许CORS。
  2. 我也尝试在$ http和node app两个angular度设置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'); } } 

angular

  $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 }); 

我的问题/我不明白的事情

  1. 这是因为会话cookie没有在浏览器中设置导致问题
  2. 如果它涉及CORS,我错过了任何设置?
  3. 还有什么????

我基于@robertklep评论自己解决这个问题。 基本上,passportjs设置没有任何问题。 这是关于如何以angular度发送withCredentials标志。 而不是调用$ http的get或post方法。 我使用下面的格式,它适用于我

 $http({ method: 'GET', url: 'xxxx', data: {...}, withCredentials: true }).success .... 

参考: https : //docs.angularjs.org/api/ng/service/ $ http#用法

如果您的login服务请求包含“withCredentials”configuration选项,那么如果您提供了正确的login信息,passport.js会将凭据附加到请求中。

 $http({ method: 'POST', url: 'http://xxxxx/login', data: {...}, withCredentials: true})