Created
March 20, 2020 02:01
-
-
Save mozhu1024/63c8299d9d3a7c95d8a608a311db4e92 to your computer and use it in GitHub Desktop.
[CSRF Middleware in Gin] #gin #csrf #middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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