CSRF prevention for the Golang Revel framework.

Related tags

Forms revel-csrf
Overview

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
Issues
  • 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.

    opened by ottob 4
  • 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

    opened by verdverm 3
  • 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

    opened by u007 1
  • 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
    opened by ghost 1
  • 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
    
    opened by verdverm 1
  • 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.

    opened by dndx 1
  • 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.

    opened by akensho 1
Owner
Christophe Bonello
Dart, Flutter, Go and JavaScript
Christophe Bonello
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

Justinas Stankevičius 1.3k Aug 8, 2022
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

Lee Benson 263 Jul 14, 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

Vladimir Mihailenco 39 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

Alessandro Frossi 69 Aug 4, 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

Michael Nelson 98 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

Gorilla Web Toolkit 816 Aug 1, 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

Gorilla Web Toolkit 816 Aug 1, 2022
fastglue-csrf implements CSRF middleware for fastglue.

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

Joe Paul 13 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.

Flamego 7 Jul 29, 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,

null 88 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,

null 88 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

Tri R.A. Wibowo 0 Dec 25, 2021
Cossack Labs 1k Aug 4, 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

Adrian Shum 116 May 17, 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

Mike Cat 0 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

Justinas Stankevičius 1.3k Aug 8, 2022
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 解释器?希望这个仓库能给你答案

Dai Jie 11.1k Aug 8, 2022
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.

Go Condor 35 May 15, 2022
laravel for golang,goal,fullstack framework,api framework

laravel for golang,goal,fullstack framework,api framework

桥边红药 17 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 Flamingo is a web framework based on Go. It is designed to build pluggable and maintainable web projects. It is production ready, f

Flamingo 305 Aug 4, 2022
Golanger Web Framework is a lightweight framework for writing web applications in Go.

/* Copyright 2013 Golanger.com. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except

golanger 299 Mar 3, 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 Flamingo is a web framework based on Go. It is designed to build pluggable and maintainable web projects. It is production ready, f

Flamingo 306 Aug 4, 2022
Golanger Web Framework is a lightweight framework for writing web applications in Go.

/* Copyright 2013 Golanger.com. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except

golanger 299 Mar 3, 2022
The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework.

jin About The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework. If thi

null 8 Jul 14, 2022
Rpcx-framework - An RPC microservices framework based on rpcx, simple and easy to use, ultra fast and efficient, powerful, service discovery, service governance, service layering, version control, routing label registration.

RPCX Framework An RPC microservices framework based on rpcx. Features: simple and easy to use, ultra fast and efficient, powerful, service discovery,

ZYallers 1 Jan 5, 2022
terraform-plugin-mux Example (framework + framework)

Terraform Provider Scaffolding (Terraform Plugin Framework) This template repository is built on the Terraform Plugin Framework. The template reposito

Brian Flad 0 Feb 8, 2022
[Crawler/Scraper for Golang]🕷A lightweight distributed friendly Golang crawler framework.一个轻量的分布式友好的 Golang 爬虫框架。

Goribot 一个分布式友好的轻量的 Golang 爬虫框架。 完整文档 | Document !! Warning !! Goribot 已经被迁移到 Gospider|github.com/zhshch2002/gospider。修复了一些调度问题并分离了网络请求部分到另一个仓库。此仓库会继续

null 208 Jul 4, 2022
Go (Golang) API REST with Gin FrameworkGo (Golang) API REST with Gin Framework

go-rest-api-aml-service Go (Golang) API REST with Gin Framework 1. Project Description Build REST APIs to support AML service with the support of exte

Tony Aizize 1 Nov 21, 2021
Gin is a HTTP web framework written in Go (Golang).

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

Gin-Gonic 61.7k Aug 7, 2022