csrf

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2023 License: MIT Imports: 16 Imported by: 2

README

csrf

GitHub Workflow Status Codecov GoDoc Sourcegraph

Package csrf is a middleware that generates and validates CSRF tokens for Flamego.

Installation

The minimum requirement of Go is 1.18.

go get github.com/flamego/csrf

Getting started

<!-- templates/protected.tmpl -->
<form action="/protected" method="POST">
  <input type="hidden" name="_csrf" value="{{.CSRFToken}}">
  <button>Submit</button>
</form>
package main

import (
	"net/http"

	"github.com/flamego/csrf"
	"github.com/flamego/flamego"
	"github.com/flamego/session"
	"github.com/flamego/template"
)

func main() {
	f := flamego.Classic()
	f.Use(template.Templater())
	f.Use(session.Sessioner())
	f.Use(csrf.Csrfer())

	// Simulate the authentication of a session. If the "userID" exists,
	// then redirect to a form that requires CSRF protection.
	f.Get("/", func(c flamego.Context, s session.Session) {
		if s.Get("userID") == nil {
			c.Redirect("/login")
			return
		}
		c.Redirect("/protected")
	})

	// Set uid for the session.
	f.Get("/login", func(c flamego.Context, s session.Session) {
		s.Set("userID", 123)
		c.Redirect("/")
	})

	// Render a protected form by passing a CSRF token using x.Token().
	f.Get("/protected", func(c flamego.Context, s session.Session, x csrf.CSRF, t template.Template, data template.Data) {
		if s.Get("userID") == nil {
			c.Redirect("/login", http.StatusUnauthorized)
			return
		}

		// Pass token to the protected template.
		data["CSRFToken"] = x.Token()
		t.HTML(http.StatusOK, "protected")
	})

	// Apply CSRF validation to route.
	f.Post("/protected", csrf.Validate, func(c flamego.Context, s session.Session, t template.Template) {
		if s.Get("userID") != nil {
			c.ResponseWriter().Write([]byte("You submitted with a valid CSRF token"))
			return
		}
		c.Redirect("/login", http.StatusUnauthorized)
	})

	f.Run()
}

Getting help

License

This project is under the MIT License. See the LICENSE file for the full license text.

Documentation

Overview

Package csrf is a middleware that generates and validates CSRF tokens for Flamego.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Csrfer

func Csrfer(opts ...Options) flamego.Handler

Csrfer returns a middleware handler that injects csrf.CSRF into the request context, and only generates a new CSRF token on every GET request.

func GenerateToken

func GenerateToken(key, userID, actionID string) string

GenerateToken returns a URL-safe secure XSRF token that expires in 24 hours.

The key is a secret key for your application, userID is a unique identifier for the user, actionID is the action the user is taking (e.g. POSTing to a particular path).

func ValidToken

func ValidToken(token, key, userID, actionID string) bool

ValidToken returns true if token is a valid and unexpired.

func Validate

func Validate(ctx flamego.Context, x CSRF)

Validate should be used as a per route middleware to validate CSRF tokens.

Types

type CSRF

type CSRF interface {
	// Token returns the current token. This is typically used to populate a hidden
	// form in an HTML template.
	Token() string
	// ValidToken validates the passed token against the existing Secret and ID.
	ValidToken(t string) bool
	// Error executes the error function with given http.ResponseWriter.
	Error(w http.ResponseWriter)
	// Validate validates CSRF using given context. It attempts to get the token
	// from the HTTP header and then the form value. If any of these is found, the
	// token will be validated using ValidToken. If the validation fails, custom
	// Error is sent as the response. If neither the header nor form value is found,
	// http.StatusBadRequest is sent.
	Validate(ctx flamego.Context)
}

CSRF represents a CSRF service and is used to get the current token and validate a suspect token.

type Options

type Options struct {
	// Secret is the secret value used to generate tokens. Default is an
	// auto-generated 10-char random string.
	Secret string
	// Header specifies which HTTP header to be used to set and get token. Default
	// is "X-CSRF-Token".
	Header string
	// Form specifies which form value to be used to set and get token. Default is
	// "_csrf".
	Form string
	// SessionKey is the session key used to get the unique ID of users. Default is
	// "userID".
	SessionKey string
	// SetHeader indicates whether to send token via Header. Default is false.
	SetHeader bool
	// NoOrigin indicates whether to disallow Origin appear in the request header.
	// Default is false.
	NoOrigin bool
	// ErrorFunc defines the function to be executed when ValidToken fails.
	ErrorFunc func(w http.ResponseWriter)
}

Options contains options for the csrf.Csrfer middleware.

Jump to

Keyboard shortcuts

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