CSRF protection middleware for Gin. This middleware has to be used with gin-contrib/sessions.
Original credit to tommy351, this fork makes it work with gin-gonic contrib sessions.
$ go get github.com/utrack/gin-csrf
package main
import (
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/utrack/gin-csrf"
)
func main() {
r := gin.Default()
store := cookie.NewStore([]byte("secret"))
r.Use(sessions.Sessions("mysession", store))
r.Use(csrf.Middleware(csrf.Options{
Secret: "secret123",
ErrorFunc: func(c *gin.Context) {
c.String(400, "CSRF token mismatch")
c.Abort()
},
}))
r.GET("/protected", func(c *gin.Context) {
c.String(200, csrf.GetToken(c))
})
r.POST("/protected", func(c *gin.Context) {
c.String(200, "CSRF token is valid")
})
r.Run(":8080")
}