Skip to content

Instantly share code, notes, and snippets.

@mozhu1024
Created March 20, 2020 02:01
Show Gist options
  • Save mozhu1024/63c8299d9d3a7c95d8a608a311db4e92 to your computer and use it in GitHub Desktop.
Save mozhu1024/63c8299d9d3a7c95d8a608a311db4e92 to your computer and use it in GitHub Desktop.
[CSRF Middleware in Gin] #gin #csrf #middleware
func csrfMiddleware(c *gin.Context) {
method := strings.ToUpper(c.Request.Method)
if method == "POST" || method == "PUT" || method == "DELETE" {
if _csrf, err := CSRFToken(c.GetHeader("X-Csrf-Token")); err != nil || _csrf != "csrf" {
logger.Errorln(err, _csrf)
c.AbortWithStatusJSON(http.StatusBadRequest, Resp{
Code: -1,
Msg: "CSRF Validate Error",
})
return
}
}
csrf := MD5(RandomString())
_, _ = CSRFToken(csrf, "csrf")
c.Header("X-Csrf-Token", csrf)
c.Next()
}
// CSRFToken - save token in session / redis / others
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment