Gin 與 Vue2 前後臺分離跨域攜帶 cookie問題
因專案需要,前端採用 vue2+axios 開發,後端採用 Go語言 gin 框架,此時想實現前後臺分離跨域的情況下攜帶 cookie。
Vue 前端地址及埠 http://localhost:8080/
Go 後端地址及埠 http://localhost:8090/
1.前端 axios.defaults.withCredentials 設定為 true
axios.defaults.withCredentials = true
下圖
2.後端跨域中介軟體設定
package middleware import ( "github.com/gin-gonic/gin" "net/http" ) //Cors 跨域中介軟體 func Cors() gin.HandlerFunc { return func(ctx *gin.Context) { //以下是引用跨域 cookie ctx.Writer.Header().Set("Access-Control-Allow-Origin", ctx.GetHeader("Origin")) ctx.Writer.Header().Set("Access-Control-Allow-Headers", "X-Requested-With,Content-Type") ctx.Writer.Header().Set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS") ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true") //如果請求方法為 options 則寫入200 if ctx.Request.Method == http.MethodOptions { ctx.AbortWithStatus(http.StatusOK) } else { ctx.Next() } } }
注意 Access-Control-Allow-Origin 不能設定為 * ,要設定為前端的域名(http://localhost:8080/)或者直接用 ctx.GetHeader("Origin"),另 Access-Control-Allow-Credentials 必須設定為 true。
3.Gin 後端 session 、Cookie 設定
session 包我用的下面兩個
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
r:=gin.Default() //配置session store := cookie.NewStore([]byte("secret")) store.Options(sessions.Options{ Path: "/", MaxAge: 0, Secure: true, SameSite: 4, }) r.Use(sessions.Sessions("MY_SESSION_ID", store))
這裡需要注意:
Secure 需要設定為 true
SameSite 需要設定為 4
谷歌低版本瀏覽器(低於Chrome 80) SameSite 使用預設值也可以正常使用,但谷歌瀏覽器從 Chrome 80 版本中預設遮蔽所有第三方 Cookie,即預設為所有 Cookie 加上 SameSite=Lax 屬性,並且拒絕非Secure的Cookie設為 SameSite=None
所以 SameSite 需設定為 4,即 None。
參考資料:
https://www.ruanyifeng.com/blog/2019/09/cookie-samesite.html
https://blog.csdn.net/carry_chenxiaodong/article/details/114281994