CSRF prevention for the Golang Revel framework.

revel-csrf

revel-csrf implements Cross-Site Request Forgery (CSRF) attacks prevention for the Revel framework.

Code is based on the nosurf package implemented by Justinas Stankevičius.

Installation

go get github.com/cbonello/revel-csrf

A demo application is provided in the samples directory. To launch it:

revel run github.com/cbonello/revel-csrf/samples/demo

Configuration options

Revel-csrf supports following configuration options in app.conf:

  • csrf.ajax A boolean value that indicates whether or not revel-csrf should support the injection and verification of CSRF tokens for XMLHttpRequests. Default value is false.

  • csrf.token.length An integer value that defines the number of characters that should be found within CSRF tokens. Token length should be in [32..512] and default value is 32 characters.

Operating instructions

Simply call the CSRFFilter() filter in app/init.go.

package app

import (
    "github.com/cbonello/revel-csrf"
    "github.com/revel/revel"
)

func init() {
    // Filters is the default set of global filters.
    revel.Filters = []revel.Filter{
	    revel.PanicFilter,             // Recover from panics and display an error page instead.
	    revel.RouterFilter,            // Use the routing table to select the right Action
	    revel.FilterConfiguringFilter, // A hook for adding or removing per-Action filters.
	    revel.ParamsFilter,            // Parse parameters into Controller.Params.
	    revel.SessionFilter,           // Restore and write the session cookie.
	    revel.FlashFilter,             // Restore and write the flash cookie.
	     csrf.CSRFFilter,              // CSRF prevention.
	    revel.ValidationFilter,        // Restore kept validation errors and save new ones from cookie.
	    revel.I18nFilter,              // Resolve the requested language
	    revel.InterceptorFilter,       // Run interceptors around the action.
	    revel.ActionInvoker,           // Invoke the action.
    }
}

Insert a hidden input field named csrf_token in your forms.

<form action="/Hello" method="POST">
    <input type="text" name="name" />
    <input type="hidden" name="csrf_token" value="{{ .csrf_token }}" />
    <button type="submit">Send</button>
</form>

Javascript-code sample to perform AJAX calls with jQuery 1.5 and newer.

function csrfSafeMethod(method) {
    // HTTP methods that do not require CSRF protection.
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: false,
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRF-Token", {{ .csrf_token }});
        }
    }
});

$("#AJAXForm").submit(function(event){
	event.preventDefault();
    $.ajax({
        type: "POST",
        url: "/Hello",
        data: {
            name: $("#AJAXFormName").val()
        },
        success: function(data) {
            // Switch to HTML code returned by server on success.
            jQuery("body").html(data);
        },
        error: function(jqXHR, status, errorThrown) {
            alert(jqXHR.statusText);
        },
    });
});

You can call csrf.ExemptedFullPath() or csrf.ExemptedGlob() to exempt routes from CSRF checks. See app/init.go in demo application.

TODO

  • Unique token per-page.
  • Test cases.

CONTRIBUTORS

  • Otto Bretz
  • Allen Dang
Owner
Christophe Bonello
Dart, Flutter, Go and JavaScript
Christophe Bonello
Comments
  • Support multipart?

    Support multipart?

    Thanks for this filter, it's working great but I have found one small issue. I have a form with enctype="multipart/form-data", my guess is that this causes problems with sentToken = r.PostFormValue(fieldName). In this case my sentToken becomes an empty string and the csrf check fails.

  • CSRF tokens don't work with secure cookies

    CSRF tokens don't work with secure cookies

    when I set cookies.secure=true in app.conf

    csrf tokens get regenerated with each request to the server

    not sure if this is a revel-csrf issue or revel's decryption cookies failing

  • crashes on production

    crashes on production

    i found my production server crash without notice. when more than 1 users access the system from another machine, it somehow crashed

    i ran manually your plugin with: csrf.CSRFFilter(c, fc)

    what could be the issue?

    thanks

  • Revel tests and CSRF protected application

    Revel tests and CSRF protected application

    Has anybody ever used Revel tests with CSRF protected application? How tests can get CSRF token?

    I can come up with the following solutions:

    1. Parse some page and get token
    2. Create an action which will return token when in dev mode.

    Is there a better (less workaroundish) solution? How is this problem being solved in other frameworks?

    Here is what I've managed to find:

    1. Node.js/Express related solution: http://stackoverflow.com/questions/18773846/how-to-test-endpoints-protected-by-csrf-in-node-js-express
      • Parse cookie received by tests and find token there
      • When in dev mode use a constant for token rather than a random string
    2. SAP in response to GET request with header X-CSRF-Token Value : Fetch returns token: https://scn.sap.com/thread/3484244
  • update robfig references

    update robfig references

    revel moved to github.com/revel/revel

    this is the error generated:

    cannot use csrf.CSRFFilter (type func(*"github.com/robfig/revel".Controller, []"github.com/robfig/revel".Filter)) as type "github.com/revel/revel".Filter in array element
    
  • Whitelisted WS method, fixing issue that WS connection hang up before ev...

    Whitelisted WS method, fixing issue that WS connection hang up before ev...

    Took me 30 minutes to troubleshoot this problem. Revel use "WS" as method name of WebSocket requests, and we do not want to check CSRF token on WebSocket connection.

  • revel.Controller has no field or method RenderArgs

    revel.Controller has no field or method RenderArgs

  • Updated to support Revel release 0.14.0

    Updated to support Revel release 0.14.0

    Hi, revel-csrf does not work because of update revel/revel.

    According to this release infomation, function RenderArgs renamed to ViewArgs.

    My commit has followed this change.

    Could you merge this PR?

    Thank you.

Related tags
CSRF protection middleware for Go.

nosurf nosurf is an HTTP package for Go that helps you prevent Cross-Site Request Forgery attacks. It acts like a middleware and therefore is compatib

Jan 8, 2023
Trims, sanitizes & scrubs data based on struct tags (go, golang)

Conform- keep user input in check (go, golang) Trim, sanitize, and modify struct string fields in place, based on tags. Update Jan 12, 2016 -- Now als

Dec 20, 2022
HTML forms for Golang

HTML forms for Golang Installation: go get github.com/vmihailenco/gforms Example Example: package blog import ( "net/http" "github.com/vmih

Apr 3, 2020
Golang Forms made easy.

Go-FORM-it Description go-form-it makes form creation and handling easy. It allows the creation of form without having to write HTML code or bother to

Aug 20, 2022
Data validation, cleaning and error collection for golang

GoForms - form data validation, cleaning and error reporting The goforms library is a proof-of-concept for a data validation, cleaning and error colle

Jan 14, 2022
gorilla/csrf provides Cross Site Request Forgery (CSRF) prevention middleware for Go web applications & services 🔒

gorilla/csrf gorilla/csrf is a HTTP middleware library that provides cross-site request forgery (CSRF) protection. It includes: The csrf.Protect middl

Dec 26, 2022
gorilla/csrf provides Cross Site Request Forgery (CSRF) prevention middleware for Go web applications & services 🔒

gorilla/csrf gorilla/csrf is a HTTP middleware library that provides cross-site request forgery (CSRF) protection. It includes: The csrf.Protect middl

Jan 9, 2023
fastglue-csrf implements CSRF middleware for fastglue.

fastglue-csrf Overview fastglue-csrf implements CSRF middleware for fastglue.

Jan 5, 2022
Package csrf is a middleware that generates and validates CSRF tokens for Flamego

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

Nov 25, 2022
Goal is a toolkit for high productivity web development in Go language in the spirit of Revel Framework that is built around the concept of code generation.

Goal Goal is a set of tools for high productivity web development in Go language. Goal, being mostly inspired by Revel Framework and its discussions,

Sep 27, 2021
Goal is a toolkit for high productivity web development in Go language in the spirit of Revel Framework that is built around the concept of code generation.

Goal Goal is a set of tools for high productivity web development in Go language. Goal, being mostly inspired by Revel Framework and its discussions,

Sep 27, 2021
WeChat Official Account's Verification using Revel

Welcome to Revel A high-productivity web framework for the Go language. Start the web server: revel run myapp Go to http://localhost:9000/ and you'll

Dec 25, 2021
Dec 28, 2022
A multi-level cache library with stampede prevention for Go

HybridCache A multi-level cache library with cache stampede prevention for Go import "github.com/cshum/hybridcache" // Redis cache adapter based on R

Nov 21, 2022
golang csrf react example, using gorilla/mux and gorilla/mux

Demo REST backend Gorilla csrf middleware and Js frontend Use gorilla/mux and gorilla/csrf How to run open goland IDE, run middleware_test.go by click

Feb 2, 2022
CSRF protection middleware for Go.

nosurf nosurf is an HTTP package for Go that helps you prevent Cross-Site Request Forgery attacks. It acts like a middleware and therefore is compatib

Jan 8, 2023
7 days golang programs from scratch (web framework Gee, distributed cache GeeCache, object relational mapping ORM framework GeeORM, rpc framework GeeRPC etc) 7天用Go动手写/从零实现系列

7 days golang programs from scratch README 中文版本 7天用Go从零实现系列 7天能写什么呢?类似 gin 的 web 框架?类似 groupcache 的分布式缓存?或者一个简单的 Python 解释器?希望这个仓库能给你答案

Jan 5, 2023
GoCondor is a golang web framework with an MVC like architecture, it's based on Gin framework
GoCondor is a golang web framework with an MVC like architecture, it's based on Gin framework

GoCondor is a golang web framework with an MVC like architecture, it's based on Gin framework, it features a simple organized directory structure for your next project with a pleasant development experience, made for developing modern APIs and microservices.

Dec 29, 2022
laravel for golang,goal,fullstack framework,api framework
laravel for golang,goal,fullstack framework,api framework

laravel for golang,goal,fullstack framework,api framework

Feb 24, 2022
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.

Flamingo Framework Flamingo is a web framework based on Go. It is designed to build pluggable and maintainable web projects. It is production ready, f

Jan 5, 2023