跨域Cookie Golang ReactJs

huangapple go评论61阅读模式
英文:

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,
	})

huangapple
  • 本文由 发表于 2022年4月20日 12:13:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/71934019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定