xsrf

package
v0.0.0-...-a70aae3 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2024 License: Apache-2.0 Imports: 15 Imported by: 17

Documentation

Overview

Package xsrf provides Cross Site Request Forgery prevention middleware.

Usage:

  1. When serving GET request put hidden "xsrf_token" input field with the token value into the form. Use TokenField(...) to generate it.
  2. Wrap POST-handling route with WithTokenCheck(...) middleware.

Index

Constants

View Source
const XSRFTokenMetadataKey = "x-xsrf-token"

XSRFTokenMetadataKey is the gRPC metadata key with the XSRF token.

Variables

This section is empty.

Functions

func Check

func Check(ctx context.Context, tok string) error

Check returns nil if XSRF token is valid.

func Interceptor

func Interceptor(method auth.Method) grpcutil.UnifiedServerInterceptor

Interceptor returns a server interceptor that check the XSRF token if the call was authenticated through the given method (usually some sort of cookie-based authentication).

The token should be in the incoming metadata at "x-xsrf-token" key.

This is useful as a defense in depth against unauthorized cross-origin requests when using pRPC APIs with cookie-based authentication. Theoretically CORS policies and SameSite cookies can also solve this problem, but their semantics is pretty complicated and it is easy to mess up.

func Token

func Token(ctx context.Context) (string, error)

Token generates new XSRF token bound to the current caller.

The token is URL safe base64 encoded string. It lives for 4 hours and may potentially be used multiple times (i.e. the token is stateless).

Put it in hidden form field under the name of "xsrf_token", e.g. <input type="hidden" name="xsrf_token" value="{{.XsrfToken}}">.

Later WithTokenCheck will grab it from there and verify its validity.

func TokenField

func TokenField(ctx context.Context) template.HTML

TokenField generates "<input type="hidden" ...>" field with the token.

It can be put into HTML forms directly. Panics on errors.

func WithTokenCheck

func WithTokenCheck(c *router.Context, next router.Handler)

WithTokenCheck is middleware that checks validity of XSRF tokens.

If searches for the token in "xsrf_token" POST form field (as generated by TokenField). Aborts the request with HTTP 403 if XSRF token is missing or invalid.

Types

This section is empty.

Jump to

Keyboard shortcuts

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