英文:
Cross Domain Cookie Golang ReactJs
问题
在Go语言中,我正在为前端设置cookie:
http.SetCookie(w, &http.Cookie{
Name: "jwt-token",
Value: tokenString,
Expires: expirationTime,
})
此外,我还在Go语言中设置了以下响应头:
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上,前端部署在https://domainB.com上。前端可以从响应头中接收到来自后端的cookie,但是在请求头中没有发送cookie给后端。
如何解决这个问题?
英文:
In Go, I am setting the cookie for frontend:
http.SetCookie(w, &http.Cookie{
Name: "jwt-token",
Value: tokenString,
Expires: expirationTime,
})
Also, I am setting these response headers in Go:
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")
This backend is deployed on https://domainA.com, and the frontend is deployed on https://domainB.com. The frontend is receiving the cookie from this backend in the response header, but it is not sending the cookie to backend in request header.
How to solve this issue?
答案1
得分: 0
对于您的情况,您需要在响应头的Set-Cookie中添加Path=/;。这样,在成功登录后,响应中的cookie将被添加到后续的请求中。
英文:
For your case, you need to add Path=/; into Set-Cookie in response headers. So that the cookie from response could be added to sequenced requests after successful login.
答案2
得分: 0
通过将 cookie 设置为以下内容解决了问题(使用了 SameSite):
http.SetCookie(w, &http.Cookie{
Name: "jwt-token",
Value: tokenString,
Expires: expirationTime,
SameSite: http.SameSiteNoneMode,
Secure: true,
})
英文:
Solved by updating setting the cookie to this (used SameSite):
http.SetCookie(w, &http.Cookie{
Name: "jwt-token",
Value: tokenString,
Expires: expirationTime,
SameSite: http.SameSiteNoneMode,
Secure: true,
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论