Express-session Secure Cookies not working

依然范特西╮ 提交于 2019-12-02 03:05:40

问题


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.


回答1:


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:

  • plain XHR: look at the example code
  • fetch: here
  • jQuery: use the xhrFields option for $.ajax()
  • Angular 1: here
  • Angular 2: here



回答2:


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:


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.



来源:https://stackoverflow.com/questions/44039069/express-session-secure-cookies-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!