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

 

posted on 2022-03-14 14:43  沈恩忍  阅读(793)  评论(1编辑  收藏  举报

导航