CloudFlare set-cookie没有传递给浏览器

时间:2017-09-19 06:29:15

标签: express cloudflare passport.js passport-local express-session

我在CloudFlare背后有一个明确的应用程序。在开发中,Set-Cookie标头在登录时传递,但在CloudFlare之后,不传递Set-Cookie标头。有什么建议?我的配置是:

```     从护照进口护照'     从' cookie-parser'中导入cookieParser;     来自' express-session'的导入会话;     从护照本地'导入{策略为LocalStrategy};     从' ../../ db / sequelize / passport';

导入localPassport
const secret = 'foo';

const authenticationMiddleware = (req, res, next) => {
  console.log('authenticated', req.isAuthenticated());

  if (req.isAuthenticated()) {
    next();
  } else if (req.url.includes('/rest/')) {
    res.status(401).send('Unauthorized');
  } else {
    res.status(302).redirect('/admin/login');
  }
};

const sessionSecurity = (app) => {
  app.set('trust proxy', 1);
  app.use(cookieParser(secret));
  app.use(
    session({
      secret,
      proxy: true, 
      saveUninitialized: false,
      resave: false,
      maxAge: null,
      cookie: {
        path: '/admin',
        secure: process.env.NODE_ENV === 'production',
      },
    }),
  ); // session secret
  app.use(passport.initialize());
  app.use(passport.session());

  passport.use(new LocalStrategy(localPassport.local));
  passport.serializeUser((user, done) => {
    done(null, user.id);
  });
  passport.deserializeUser(localPassport.deserializeUser);

  app.post('/admin/login', (req, res, next) => {
    passport.authenticate('local', (authErr, user) => {
      if (authErr) return next(new Error(authErr));
      if (!user) {
        return res.sendStatus(401);
      }
      return req.logIn(user, (loginErr) => {
        if (loginErr) return res.sendStatus(401);
        return res.sendStatus(200);
      });
    })(req, res, next);
  });

  app.post('/admin/logout', (req, res) => {
    req.logOut();

    req.session.destroy(() => {
      res
        .clearCookie('connect.sid', { path: '/admin' })
        .sendStatus(200);
    });
  });

  app.get('/admin/rest/*', authenticationMiddleware);

  app.get('/admin/rest/status', (req, res) => {
    res.sendStatus(200);
  });

};

```

2 个答案:

答案 0 :(得分:1)

这是因为设置为cookie安全的服务器设置以及CloudFlare和我的服务器之间的连接不是。

答案 1 :(得分:0)

在设置cloudflare(加密标签)时,我打开了“Authenticated Origin Pulls”并在“app.js”(来自我的应用)中添加了此app.set('trust proxy', 1);app.use(session({...})之前,我的问题解决了。