Express-session Secure Cookies not working

2019-07-25 16:59发布

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.

3条回答
仙女界的扛把子
2楼-- · 2019-07-25 17:26

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

查看更多
等我变得足够好
3楼-- · 2019-07-25 17:41

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.

查看更多
混吃等死
4楼-- · 2019-07-25 17:42

My guess is that the actual problem is this:

httpOnly: true

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 set withCredentials before any cookies will be sent in the request.

It depends on which client-side setup you're using how to do that:

查看更多
登录 后发表回答