3

I have an express application behind CloudFlare. In development, the Set-Cookie header gets passed on login, but behind CloudFlare, the Set-Cookie header is not passed. Any suggestions? My config is:

``` import passport from 'passport'; import cookieParser from 'cookie-parser'; import session from 'express-session'; import { Strategy as LocalStrategy } from 'passport-local'; import localPassport from '../../db/sequelize/passport';

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 Answers 2

4

This was caused because the server settings where set to cookie secure and the connection between CloudFlare and my server were not.

2
  • 2
    Hi. I have a same problem.so what is solution?
    – ali karimi
    Commented Jun 7, 2018 at 18:31
  • @alikarimi You must set the secure cookie setting to false in your application.
    – Query
    Commented Sep 7, 2024 at 21:10
0

In setting of cloudflare (crypto tab), I turned on "Authenticated Origin Pulls" and in "app.js" (from my app) add this app.set('trust proxy', 1); before app.use(session({...}) and my problem solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.