简体   繁体   中英

How to set HttpOnly flag In Node.js ,Express.js application?

Hi I have a project in node.js and I want to set the HttpOnly flag: true for header response.

I have written the following code in app.js but it make no effect in response header.

app.use(session({
 secret: "notagoodsecretnoreallydontusethisone",
 resave: false,
 saveUninitialized: true,
 cookie: {httpOnly: true, secure: true}
}));

So any suggestion for setting HttpOnly Flag in express.js is most welcome.

I think you could try this!

app.use(session({
   cookieName: 'sessionName',
   secret: "notagoodsecretnoreallydontusethisone",
   resave: false,
   saveUninitialized: true,
   httpOnly: true,  // dont let browser javascript access cookie ever
   secure: true, // only use cookie over https
   ephemeral: true // delete this cookie while browser close
}));

This example uses cookie-parser library.

Setting a cookie: res.cookie("cookie_name", token, {})

Pass res.cookie() an options object with httpOnly: true ,

 const options = {
    expires: duration,
    httpOnly: true,
  };

Final eg

res.cookie("cookie_name", token, options)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM