跨站请求伪造(英语:Cross-Site Request Forgery),也被称为 one-click attack 或者 session riding,通常缩写为 CSRF 或者 XSRF, 是一种挟制用户在当前已登录的Web应用程序上执行非本意的操作的攻击方法。跟跨网站脚本(XSS)相比,XSS利用的是用户对指定网站的信任,CSRF 利用的是网站对用户网页浏览器的信任。
这里我们选择通过token的方式对请求进行校验,通过中间件的方式实现,CSRF跨站点防御插件由社区包提供。
开发者可以通过对接口添加中间件的方式,增加token校验功能。
感兴趣的朋友可以阅读插件源码 https://github.com/gogf/csrf
import "github.com/gogf/csrf"
csrf插件支持自定义csrf.Config配置,Config中的Cookie.Name是中间件设置到请求返回Cookie中token的名称,ExpireTime是token超时时间,TokenLength是token长度,TokenRequestKey是后续请求需求带上的参数名。
s := g.Server()
s.Group("/api.v2", func(group *ghttp.RouterGroup) {
group.Middleware(csrf.NewWithCfg(csrf.Config{
Cookie: &http.Cookie{
Name: "_csrf",// token name in cookie
},
ExpireTime: time.Hour * 24,
TokenLength: 32,
TokenRequestKey: "X-Token",// use this key to read token in request param
}))
group.ALL("/csrf", func(r *ghttp.Request) {
r.Response.Writeln(r.Method + ": " + r.RequestURI)
})
})
通过配置后,前端在POST请求前从Cookie中读取_csrf的值(即token),然后请求发出时将token以X-Token(TokenRequestKey所设置)参数名置入请求中(可以是Header或者Form)即可通过token校验。
package main
import (
"net/http"
"time"
"github.com/gogf/csrf"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
// default cfg
func main() {
s := g.Server()
s.Group("/api.v2", func(group *ghttp.RouterGroup) {
group.Middleware(csrf.New())
group.ALL("/csrf", func(r *ghttp.Request) {
r.Response.Writeln(r.Method + ": " + r.RequestURI)
})
})
s.SetPort(8199)
s.Run()
}
package main
import (
"net/http"
"time"
"github.com/gogf/csrf"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
// set cfg
func main() {
s := g.Server()
s.Group("/api.v2", func(group *ghttp.RouterGroup) {
group.Middleware(csrf.NewWithCfg(csrf.Config{
Cookie: &http.Cookie{
Name: "_csrf",// token name in cookie
Secure: true,
SameSite: http.SameSiteNoneMode,// 自定义samesite
},
ExpireTime: time.Hour * 24,
TokenLength: 32,
TokenRequestKey: "X-Token",// use this key to read token in request param
}))
group.ALL("/csrf", func(r *ghttp.Request) {
r.Response.Writeln(r.Method + ": " + r.RequestURI)
})
})
s.SetPort(8199)
s.Run()
}
备案信息: 粤ICP备15087711号-2
Copyright © 2008-2024 啊嘎哇在线工具箱 All Rights.
本站所有资料来源于网络,版权归原作者所有,仅作学习交流使用,如不慎侵犯了您的权利,请联系我们。