csrf

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2016 License: BSD-3-Clause Imports: 5 Imported by: 2

README

CSRF(Cross-Site Request Forgery) attack protection

Build Status GoDoc

CSRF package for Golang, it provides CSRF(Cross-Site Request Forgery) attack protection.

Installation

go get github.com/clevergo/csrf

Usage

package main

import (
	"github.com/clevergo/csrf"
	"github.com/headwindfly/utils"
	"fmt"
)

func main() {
	maskLen := 8 // length of mark bytes.
	tokenLen := 32 // length of true token bytes.

	// True token bytes.
	// Note that the true token must not be exposed.
	// You can store it in session or something else, it is up to your application.
	// What's more, you just need create unique token for per session once.
	token := utils.RandomBytes(tokenLen) // You can generate bytes by other way, it is up to you.

	// Generate encoded token.
	// The encoded token should exposed to client.
	encodedToken := csrf.Generate(maskLen, token)

	// Validate the token.
	// encodedToken can be catched from request,
	// that is to say, sensitive request(such as POST request) should carry the encoded token.
	err := csrf.Validate(maskLen, []byte(encodedToken), token)
	if err != nil {
		// Handle error
		panic(err.Error())
	}

	fmt.Println("Congratulations! Encoded token is valid.")

	// Validate invalid token
	err = csrf.Validate(maskLen, []byte(encodedToken), []byte("Invalid token."))
	if err == nil {
		panic("Something wrong.")
	}
}

You can run the following command to check result.

go run $GOPATH/src/github.com/clevergo/csrf/examples/main.go

See also Example.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Generate

func Generate(maskLen int, token []byte) string

Generate CSRF token. maskLen mask length. token true token. Returns a encoded token.

func Validate

func Validate(maskLen int, encodeToken, trueToken []byte) error

Validate CSRF token. maskLen length of mask. token the token which generated by method named Generate(). trueToken true token.

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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