Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CloudFlare set-cookie not passing through to browser

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

};

```

like image 991
Marc Avatar asked Dec 02 '25 23:12

Marc


2 Answers

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

like image 131
Marc Avatar answered Dec 06 '25 17:12

Marc


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.

like image 26
ali karimi Avatar answered Dec 06 '25 17:12

ali karimi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!