如何在Cookie上指定SameSite和安全(使用axios / React / Node Express)

时间:2020-08-01 19:35:37

标签: node.js reactjs express cookies axios

我有一个已经运行了一段时间的聊天应用程序,但是突然之间,它在客户端给了我这个问题:

var enableDays=["' . implode('", "', $dates) . '"]

我在我的React客户端上使用axios:

Because a cookie's SameSite attribute was not set or is invalid, it defaults to SameSite=Lax,
which prevents the cookie from being set in a cross-site context. This behavior protects 
user data from accidentally leaking to third parties and cross-site request forgery.

Resolve this issue by updating the attributes of the cookie:
Specify SameSite=None and Secure if the cookie is intended to be set in cross-site contexts.
Note that only cookies sent over HTTPS may use the Secure attribute.

通过在我的Nodejs Express服务器中对/ signin的发布请求中执行此操作,我正在使用JWT设置Cookie

axios.defaults.withCredentials = true
axios.post('https://easytalkchatappv2.herokuapp.com/signin', {
      username: username,
      password: password
    }).then(res => {
      console.log(res.data)
})

我也在使用cookie解析器。如何将这些SameSite和Secure属性添加到Cookie?

1 个答案:

答案 0 :(得分:3)

您应该能够将'secure'和'sameSite'属性传递给res.cookie方法;如下所示,其中x替换为您要使用的值:

res.cookie('token', accessToken, { sameSite: x, secure: x })

如Express文档中所示: https://expressjs.com/en/api.html#res.cookie