csrf

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2022 License: Apache-2.0 Imports: 11 Imported by: 10

README

CSRF (This is a community driven project)

Cross-site request forgery (also known as CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform. It allows an attacker to partly circumvent the same origin policy, which is designed to prevent different websites from interfering with each other.

The CSRF middleware helps you prevent Cross-Site Request Forgery attacks.

This repo borrows the structural design of fiber-csrf and adapted to Hertz.

Install

go get github.com/hertz-contrib/csrf

import

import "github.com/hertz-contrib/csrf"

Example

package main

import (
	"context"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/hertz-contrib/csrf"
	"github.com/hertz-contrib/sessions"
	"github.com/hertz-contrib/sessions/cookie"
)

func main() {
	h := server.Default()

	store := cookie.NewStore([]byte("secret"))
	h.Use(sessions.New("session", store))
	h.Use(csrf.New(
		csrf.WithSecret("secret123"),
		csrf.WithErrorFunc(func(c context.Context, ctx *app.RequestContext) {
			ctx.String(400, ctx.Errors.Last().Error())
			ctx.Abort()
		},
		)))

	h.GET("/protected", func(c context.Context, ctx *app.RequestContext) {
		ctx.String(200, csrf.GetToken(ctx))
	})

	h.POST("/protected", func(c context.Context, ctx *app.RequestContext) {
		ctx.String(200, "CSRF token is valid")
	})

	h.Spin()
}

Options

Option Default Description
Secret "csrfSecret" Secret used to generate token.
IgnoreMethods "GET", "HEAD", "OPTIONS", "TRACE" Ignored methods will be considered no protection required.
Next nil Next defines a function to skip this middleware when returned true.
KeyLookup "header:X-CSRF-TOKEN" KeyLookup is a string in the form of ":" that is used to create an Extractor that extracts the token from the request.
ErrorFunc func(ctx context.Context, c *app.RequestContext) { panic(c.Errors.Last()) } ErrorFunc is executed when an error is returned from app.HandlerFunc.
Extractor Default will create an Extractor based on KeyLookup. Extractor returns the csrf token. If set this will be used in place of an Extractor based on KeyLookup.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var OptionsDefault = Options{
	Secret: csrfSecret,

	IgnoreMethods: []string{"GET", "HEAD", "OPTIONS", "TRACE"},
	Next:          nil,
	KeyLookup:     "header:" + csrfHeaderName,
	ErrorFunc:     func(ctx context.Context, c *app.RequestContext) { panic(c.Errors.Last()) },
}

OptionsDefault is the default options.

Functions

func CsrfFromForm

func CsrfFromForm(param string) func(ctx context.Context, c *app.RequestContext) (string, error)

CsrfFromForm returns a function that extracts a token from a multipart-form.

func CsrfFromHeader

func CsrfFromHeader(param string) func(ctx context.Context, c *app.RequestContext) (string, error)

CsrfFromHeader returns a function that extracts token from the request header.

func CsrfFromParam

func CsrfFromParam(param string) func(ctx context.Context, c *app.RequestContext) (string, error)

CsrfFromParam returns a function that extracts token from the url param string.

func CsrfFromQuery

func CsrfFromQuery(param string) func(ctx context.Context, c *app.RequestContext) (string, error)

CsrfFromQuery returns a function that extracts token from the query string.

func GetToken

func GetToken(c *app.RequestContext) string

GetToken returns a CSRF token.

func New

func New(opts ...Option) app.HandlerFunc

New validates CSRF token.

Types

type CsrfExtractorHandler

type CsrfExtractorHandler func(ctx context.Context, c *app.RequestContext) (string, error)

type CsrfNextHandler

type CsrfNextHandler func(ctx context.Context, c *app.RequestContext) bool

type Option

type Option struct {
	F func(o *Options)
}

Option is the only struct that can be used to set Options.

func WithErrorFunc

func WithErrorFunc(f app.HandlerFunc) Option

WithErrorFunc sets ErrorFunc.

func WithExtractor

func WithExtractor(f CsrfExtractorHandler) Option

WithExtractor sets extractor.

func WithIgnoredMethods

func WithIgnoredMethods(methods []string) Option

WithIgnoredMethods sets methods that do not need to be protected.

func WithKeyLookUp

func WithKeyLookUp(lookup string) Option

WithKeyLookUp sets a string in the form of "<source>:<key>" that is used to create an Extractor that extracts the token from the request.

func WithNext

func WithNext(f CsrfNextHandler) Option

WithNext sets whether to skip this middleware.

func WithSecret

func WithSecret(secret string) Option

WithSecret sets secret.

type Options

type Options struct {
	// Secret used to generate token.
	//
	// Default: csrfSecret
	Secret string

	// Ignored methods will be considered no protection required.
	//
	// Optional. Default: "GET", "HEAD", "OPTIONS", "TRACE"
	IgnoreMethods []string

	// Next defines a function to skip this middleware when returned true.
	//
	// Optional. Default: nil
	Next CsrfNextHandler

	// KeyLookup is a string in the form of "<source>:<key>" that is used
	// to create an Extractor that extracts the token from the request.
	// Possible values:
	// - "header:<name>"
	// - "query:<name>"
	// - "param:<name>"
	// - "form:<name>"
	//
	// Optional. Default: "header:X-CSRF-TOKEN"
	KeyLookup string

	// ErrorFunc is executed when an error is returned from app.HandlerFunc.
	//
	// Optional. Default: func(ctx context.Context, c *app.RequestContext) { panic(c.Errors.Last()) }
	ErrorFunc app.HandlerFunc

	// Extractor returns the csrf token.
	//
	// If set this will be used in place of an Extractor based on KeyLookup.
	//
	// Optional. Default will create an Extractor based on KeyLookup.
	Extractor CsrfExtractorHandler
}

Options defines the config for middleware.

func NewOptions

func NewOptions(opts ...Option) *Options

func (*Options) Apply

func (o *Options) Apply(opts []Option)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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