When not using secure cookie true setting, my app user login works fine. When I enable secure cookies, the login appears to go through fine, but it seems the cookie is not saved and the user is not logged in.
In other words, this works:
app = express();
app.use(session({
secret: 'secret code',
store: sessionStore,
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
maxAge: 5184000000 // 60 days
}
}));
This does not work (user isn't able to log in):
app = express();
app.set('trust proxy');
app.use(session({
secret: config.cookieSecret,
store: sessionStore,
resave: false,
saveUninitialized: false,
proxy: true,
secureProxy: true,
cookie: {
secure: true,
httpOnly: true,
maxAge: 5184000000 // 60 days
}
}));
Behind cloudflare and nginx. This is in my nginx config:
location ~ / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://localhost:3000;
}
From what I read, I think it should work. What am I missing?
EDIT: I am running https with a valid ssl cert.
That's exactly what secure cookie does. It does not get saved by the browser in an insecure environment, read
http://
.You need to add an ssl sert, redirect all http requests to https and then the cookie would get saved in the browser.
Getting https set up on local is irritating, so set
secure
in a config / environment variable you also set to false on your source control and enable it for prod/ staging.Edit: Also enable resave,
resave: true
Removing the secret key from cookie-parser seems to do the trick and allow logins for some reason. I was using the same secret key as the session cookie (as the documentation says to do) so I don't understand why it didn't work and yet it worked with unsecure cookies. Leaving the secret key on cookie-parser and enabling session resave true also worked. If anybody can explain this it would be appreciated.
My guess is that the actual problem is this:
This means that any client-side code cannot access the cookie (through
document.cookie
), and any XHR ("AJAX") requests that you perform need to explicitly setwithCredentials
before any cookies will be sent in the request.It depends on which client-side setup you're using how to do that:
xhrFields
option for$.ajax()