跨域 Cookie Golang ReactJs

Cross Domain Cookie Golang ReactJs

在 Go 中,我正在为前端设置 cookie:

http.SetCookie(w, &http.Cookie{
            Name:     "jwt-token",
            Value:    tokenString,
            Expires:  expirationTime,
        })

此外,我在 Go 中设置这些响应 headers:

w.Header().Set("Access-Control-Allow-Origin", "https://domainB.com")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,access-control-allow-origin, access-control-allow-headers,access-control-allow-credentials")
w.Header().Set("Content-Type", "application/json")

此后端部署在 https://domainA.com, and the frontend is deployed on https://domainB.com。前端在响应 header 中从该后端接收 cookie,但未在请求 header.

中将 cookie 发送到后端

如何解决这个问题?

对于你的情况,你需要添加 Path=/;进入 Set-Cookie 响应 headers。这样就可以在成功登录后将来自响应的cookie添加到顺序请求中。

通过将 cookie 设置更新为此(使用 SameSite)解决:

http.SetCookie(w, &http.Cookie{
        Name:    "jwt-token",
        Value:   tokenString,
        Expires: expirationTime,
        SameSite: http.SameSiteNoneMode,
        Secure: true,
    })