csrf

package module
v0.0.0-...-1932b6d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 23, 2021 License: MIT Imports: 7 Imported by: 0

README

gin-csrf Build Status

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.

Installation

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

Usage

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")
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetToken

func GetToken(c *gin.Context) string

GetToken returns a CSRF token.

func Middleware

func Middleware(options Options) gin.HandlerFunc

Middleware validates CSRF token.

Types

type Options

type Options struct {
	Secret        string
	IgnoreMethods []string
	ErrorFunc     gin.HandlerFunc
	TokenGetter   func(c *gin.Context) string
}

Options stores configurations for a CSRF middleware.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL