All Projects → tommy351 → gin-csrf

tommy351 / gin-csrf

Licence: MIT license
CSRF protection middleware for Gin.

Programming Languages

go
31211 projects - #10 most used programming language

gin-csrf

Build Status

CSRF protection middleware for Gin. This middleware has to be used with gin-sessions.

Installation

$ go get github.com/tommy351/gin-csrf

Usage

import (
    "errors"
    
    "github.com/gin-gonic/gin"
    "github.com/tommy351/gin-sessions"
    "github.com/tommy351/gin-csrf"
)

func main(){
    g := gin.New()
    store := sessions.NewCookieStore([]byte("secret123"))
    g.Use(sessions.Middleware("my_session", store))
    g.Use(csrf.Middleware(csrf.Options{
        Secret: "secret123",
        ErrorFunc: func(c *gin.Context){
            c.Fail(400, errors.New("CSRF token mismatch"))
        },
    }))
    
    g.GET("/protected", func(c *gin.Context){
        c.String(200, csrf.GetToken(c))
    })
    
    g.POST("/protected", func(c *gin.Context){
        c.String(200, "CSRF token is valid")
    })
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].