79116521

Date: 2024-10-23 05:49:55
Score: 0.5
Natty:
Report link

When you create gin middleware, just call the csrf.Protect function and set anonimous function as argument where you call ctx.Next()

//create gin middleware as usual
func CSRFMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        // create gorilla/csrf middleware as showed in docs
        gorillaCSRF := csrf.Protect(
            []byte("32-byte-long-auth-key"),
            // set properties as needed with csrf.<setter function>
            csrf.ErrorHandler(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
                //use context from gin-gonic instead of http writer/request
                c.JSON(http.StatusForbidden, gin.H{"error": "CSRF token mismatch"})
                c.Abort()
            })),
        )
        
        gorillaCSRF(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
            // Call next handler
            c.Next()
        })).ServeHTTP(c.Writer, c.Request)
    }
}
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Starts with a question (0.5): When you
  • Low reputation (1):
Posted by: braam76