Skip to content
/ csrf Public

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

License

Notifications You must be signed in to change notification settings

flamego/csrf

Repository files navigation

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.