csrf

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: MIT Imports: 4 Imported by: 0

README

CSRF protection

Basic protection against CSRF attacks.

Implementation

The operating principle is similar to that of Django, but a little more naive. The library sets a cookie with a random token. Every unsafe request (POST, PUT, DELETE, etc.) must contain a copy of this token in a form field or HTTP header.

Usage

r := http.NewServeMux()
csrfProtection := csrf.Default()

// You can change field or header name (as well as other settings):
// csrfProtection.FormFieldName = "foo"
// csrfProtection.HeaderName = "bar"

http.ListenAndServe(":8000", csrfProtection.Middleware(r))
Option 1

Add a hidden input to all forms that use unsafe methods:

<input type="hidden" name="{{ .CsrfFieldName }}" value="{{ .CsrfToken }}" />

Your HTTP handler may look like this:

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  template.Execute(w, map[string]string{
    "CsrfFieldName": csrfProtection.FieldName,
    "CsrfToken": csrf.GetCSRFToken(r.Context()),
  })
})
Option 2

Provide a token using JavaScript:

/**
 * Copied from https://docs.djangoproject.com/en/5.2/howto/csrf/.
 * @param {string} name - Cookie name.
 * @returns {string | null}
 */
function getCookie(name) {
  let cookieValue = null;
  if (document.cookie && document.cookie !== "") {
    const cookies = document.cookie.split(";");
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      // Does this cookie string begin with the name we want?
      if (cookie.substring(0, name.length + 1) === name + "=") {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}

async function makeRequest() {
  const csrfToken = getCookie("csrfmiddlewaretoken");
  await fetch("/handler", {
    method: "POST",
    headers: {
      "X-CSRFToken": csrfToken,
    },
  });
}

Documentation

Overview

CSRF protection.

Version: 0.0.1. Repository: https://github.com/ordinary-dev/go-sfl. License: MIT.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetCSRFToken

func GetCSRFToken(ctx context.Context) string

Get CSRF token generated by the CSRF middleware.

Types

type Protection

type Protection struct {
	CookieName    string        // Name of the cookie with the first CSRF token.
	Secure        bool          // `Secure` cookie attribute.
	SameSite      http.SameSite // `SameSite` cookie attribute.
	FormFieldName string        // Name of the form field with the second token.
	HeaderName    string        // Name of the header with the second token.
	TokenLength   uint          // Length of generated CSRF tokens in bytes (symbols).
}

func Default

func Default() Protection

Create a new instance of CSRF protection. You can tweak settings after initialization.

func (*Protection) Middleware

func (p *Protection) Middleware(next http.Handler) http.Handler

Middleware to prevent CSRF attacks.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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