All Projects → gorilla → Csrf

gorilla / Csrf

Licence: bsd-3-clause
gorilla/csrf provides Cross Site Request Forgery (CSRF) prevention middleware for Go web applications & services 🔒

Programming Languages

go
31211 projects - #10 most used programming language
golang
3204 projects

Projects that are alternatives of or similar to Csrf

Handlers
A collection of useful middleware for Go HTTP services & web applications 🛃
Stars: ✭ 1,174 (+86.05%)
Mutual labels:  middleware, gorilla
Csrf
Package csrf is a middleware that generates and validates CSRF tokens for Macaron.
Stars: ✭ 6 (-99.05%)
Mutual labels:  middleware, csrf
Csurf
CSRF token middleware
Stars: ✭ 2,183 (+245.96%)
Mutual labels:  middleware, csrf
Nosurf
CSRF protection middleware for Go.
Stars: ✭ 1,131 (+79.24%)
Mutual labels:  middleware, csrf
Mux
A powerful HTTP router and URL matcher for building Go web servers with 🦍
Stars: ✭ 15,667 (+2382.88%)
Mutual labels:  middleware, gorilla
Rill
🗺 Universal router for web applications.
Stars: ✭ 541 (-14.26%)
Mutual labels:  middleware
Gin Boilerplate
The fastest way to deploy a restful api's with Gin Framework with a structured project that defaults to PostgreSQL database and JWT authentication middleware stored in Redis
Stars: ✭ 559 (-11.41%)
Mutual labels:  middleware
Soap Client
A general purpose SOAP client for PHP
Stars: ✭ 523 (-17.12%)
Mutual labels:  middleware
Repatch
Dispatch reducers
Stars: ✭ 516 (-18.23%)
Mutual labels:  middleware
Session
Simple session middleware for Express
Stars: ✭ 5,571 (+782.88%)
Mutual labels:  middleware
Serve Favicon
favicon serving middleware
Stars: ✭ 586 (-7.13%)
Mutual labels:  middleware
Underconstruction
This Laravel 8 package makes it possible for you to set your website in "Under Construction" mode. Only users with the correct 4 (or more) digit code can access your site. 🔥 💥 🔥
Stars: ✭ 549 (-13%)
Mutual labels:  middleware
Swagger Express Middleware
Swagger 2.0 middlware and mocks for Express.js
Stars: ✭ 543 (-13.95%)
Mutual labels:  middleware
Cors
Node.js CORS middleware
Stars: ✭ 5,252 (+732.33%)
Mutual labels:  middleware
Xsrfprobe
The Prime Cross Site Request Forgery (CSRF) Audit and Exploitation Toolkit.
Stars: ✭ 532 (-15.69%)
Mutual labels:  csrf
Soapcore
SOAP extension for ASP.NET Core
Stars: ✭ 590 (-6.5%)
Mutual labels:  middleware
Body Parser
Node.js body parsing middleware
Stars: ✭ 4,962 (+686.37%)
Mutual labels:  middleware
Redux Saga
An alternative side effect model for Redux apps
Stars: ✭ 21,975 (+3382.57%)
Mutual labels:  middleware
Netdiscovery
NetDiscovery 是一款基于 Vert.x、RxJava 2 等框架实现的通用爬虫框架/中间件。
Stars: ✭ 573 (-9.19%)
Mutual labels:  middleware
Kraken Js
An express-based Node.js web application bootstrapping module.
Stars: ✭ 4,938 (+682.57%)
Mutual labels:  middleware

gorilla/csrf

GoDoc Sourcegraph Reviewed by Hound CircleCI

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

  • The csrf.Protect middleware/handler provides CSRF protection on routes attached to a router or a sub-router.
  • A csrf.Token function that provides the token to pass into your response, whether that be a HTML form or a JSON response body.
  • ... and a csrf.TemplateField helper that you can pass into your html/template templates to replace a {{ .csrfField }} template tag with a hidden input field.

gorilla/csrf is designed to work with any Go web framework, including:

gorilla/csrf is also compatible with middleware 'helper' libraries like Alice and Negroni.

Contents

Install

With a properly configured Go toolchain:

go get github.com/gorilla/csrf

Examples

gorilla/csrf is easy to use: add the middleware to your router with the below:

CSRF := csrf.Protect([]byte("32-byte-long-auth-key"))
http.ListenAndServe(":8000", CSRF(r))

...and then collect the token with csrf.Token(r) in your handlers before passing it to the template, JSON body or HTTP header (see below).

Note that the authentication key passed to csrf.Protect([]byte(key)) should be 32-bytes long and persist across application restarts. Generating a random key won't allow you to authenticate existing cookies and will break your CSRF validation.

gorilla/csrf inspects the HTTP headers (first) and form body (second) on subsequent POST/PUT/PATCH/DELETE/etc. requests for the token.

HTML Forms

Here's the common use-case: HTML forms you want to provide CSRF protection for, in order to protect malicious POST requests being made:

package main

import (
    "net/http"

    "github.com/gorilla/csrf"
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/signup", ShowSignupForm)
    // All POST requests without a valid token will return HTTP 403 Forbidden.
    // We should also ensure that our mutating (non-idempotent) handler only
    // matches on POST requests. We can check that here, at the router level, or
    // within the handler itself via r.Method.
    r.HandleFunc("/signup/post", SubmitSignupForm).Methods("POST")

    // Add the middleware to your router by wrapping it.
    http.ListenAndServe(":8000",
        csrf.Protect([]byte("32-byte-long-auth-key"))(r))
    // PS: Don't forget to pass csrf.Secure(false) if you're developing locally
    // over plain HTTP (just don't leave it on in production).
}

func ShowSignupForm(w http.ResponseWriter, r *http.Request) {
    // signup_form.tmpl just needs a {{ .csrfField }} template tag for
    // csrf.TemplateField to inject the CSRF token into. Easy!
    t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{
        csrf.TemplateTag: csrf.TemplateField(r),
    })
    // We could also retrieve the token directly from csrf.Token(r) and
    // set it in the request header - w.Header.Set("X-CSRF-Token", token)
    // This is useful if you're sending JSON to clients or a front-end JavaScript
    // framework.
}

func SubmitSignupForm(w http.ResponseWriter, r *http.Request) {
    // We can trust that requests making it this far have satisfied
    // our CSRF protection requirements.
}

Note that the CSRF middleware will (by necessity) consume the request body if the token is passed via POST form values. If you need to consume this in your handler, insert your own middleware earlier in the chain to capture the request body.

JavaScript Applications

This approach is useful if you're using a front-end JavaScript framework like React, Ember or Angular, and are providing a JSON API. Specifically, we need to provide a way for our front-end fetch/AJAX calls to pass the token on each fetch (AJAX/XMLHttpRequest) request. We achieve this by:

  • Parsing the token from the <input> field generated by the csrf.TemplateField(r) helper, or passing it back in a response header.
  • Sending this token back on every request
  • Ensuring our cookie is attached to the request so that the form/header value can be compared to the cookie value.

We'll also look at applying selective CSRF protection using gorilla/mux's sub-routers, as we don't handle any POST/PUT/DELETE requests with our top-level router.

package main

import (
    "github.com/gorilla/csrf"
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()
    csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"))

    api := r.PathPrefix("/api").Subrouter()
    api.Use(csrfMiddleware)
    api.HandleFunc("/user/{id}", GetUser).Methods("GET")

    http.ListenAndServe(":8000", r)
}

func GetUser(w http.ResponseWriter, r *http.Request) {
    // Authenticate the request, get the id from the route params,
    // and fetch the user from the DB, etc.

    // Get the token and pass it in the CSRF header. Our JSON-speaking client
    // or JavaScript framework can now read the header and return the token in
    // in its own "X-CSRF-Token" request header on the subsequent POST.
    w.Header().Set("X-CSRF-Token", csrf.Token(r))
    b, err := json.Marshal(user)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    w.Write(b)
}

In our JavaScript application, we should read the token from the response headers and pass it in a request header for all requests. Here's what that looks like when using Axios, a popular JavaScript HTTP client library:

// You can alternatively parse the response header for the X-CSRF-Token, and
// store that instead, if you followed the steps above to write the token to a
// response header.
let csrfToken = document.getElementsByName("gorilla.csrf.Token")[0].value

// via https://github.com/axios/axios#creating-an-instance
const instance = axios.create({
  baseURL: "https://example.com/api/",
  timeout: 1000,
  headers: { "X-CSRF-Token": csrfToken }
})

// Now, any HTTP request you make will include the csrfToken from the page,
// provided you update the csrfToken variable for each render.
try {
  let resp = await instance.post(endpoint, formData)
  // Do something with resp
} catch (err) {
  // Handle the exception
}

If you plan to host your JavaScript application on another domain, you can use the Trusted Origins feature to allow the host of your JavaScript application to make requests to your Go application. Observe the example below:

package main

import (
    "github.com/gorilla/csrf"
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()
    csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"), csrf.TrustedOrigins([]string{"ui.domain.com"}))

    api := r.PathPrefix("/api").Subrouter()
    api.Use(csrfMiddleware)
    api.HandleFunc("/user/{id}", GetUser).Methods("GET")

    http.ListenAndServe(":8000", r)
}

func GetUser(w http.ResponseWriter, r *http.Request) {
    // Authenticate the request, get the id from the route params,
    // and fetch the user from the DB, etc.

    // Get the token and pass it in the CSRF header. Our JSON-speaking client
    // or JavaScript framework can now read the header and return the token in
    // in its own "X-CSRF-Token" request header on the subsequent POST.
    w.Header().Set("X-CSRF-Token", csrf.Token(r))
    b, err := json.Marshal(user)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    w.Write(b)
}

On the example above, you're authorizing requests from ui.domain.com to make valid CSRF requests to your application, so you can have your API server on another domain without problems.

Google App Engine

If you're using Google App Engine, (first-generation) which doesn't allow you to hook into the default http.ServeMux directly, you can still use gorilla/csrf (and gorilla/mux):

package app

// Remember: appengine has its own package main
func init() {
    r := mux.NewRouter()
    r.HandleFunc("/", IndexHandler)
    // ...

    // We pass our CSRF-protected router to the DefaultServeMux
    http.Handle("/", csrf.Protect([]byte(your-key))(r))
}

Note: You can ignore this if you're using the second-generation Go runtime on App Engine (Go 1.11 and above).

Setting SameSite

Go 1.11 introduced the option to set the SameSite attribute in cookies. This is valuable if a developer wants to instruct a browser to not include cookies during a cross site request. SameSiteStrictMode prevents all cross site requests from including the cookie. SameSiteLaxMode prevents CSRF prone requests (POST) from including the cookie but allows the cookie to be included in GET requests to support external linking.

func main() {
    CSRF := csrf.Protect(
      []byte("a-32-byte-long-key-goes-here"),
      // instruct the browser to never send cookies during cross site requests
      csrf.SameSite(csrf.SameSiteStrictMode),
    )

    r := mux.NewRouter()
    r.HandleFunc("/signup", GetSignupForm)
    r.HandleFunc("/signup/post", PostSignupForm)

    http.ListenAndServe(":8000", CSRF(r))
}

Setting Options

What about providing your own error handler and changing the HTTP header the package inspects on requests? (i.e. an existing API you're porting to Go). Well, gorilla/csrf provides options for changing these as you see fit:

func main() {
    CSRF := csrf.Protect(
            []byte("a-32-byte-long-key-goes-here"),
            csrf.RequestHeader("Authenticity-Token"),
            csrf.FieldName("authenticity_token"),
            csrf.ErrorHandler(http.HandlerFunc(serverError(403))),
    )

    r := mux.NewRouter()
    r.HandleFunc("/signup", GetSignupForm)
    r.HandleFunc("/signup/post", PostSignupForm)

    http.ListenAndServe(":8000", CSRF(r))
}

Not too bad, right?

If there's something you're confused about or a feature you would like to see added, open an issue.

Design Notes

Getting CSRF protection right is important, so here's some background:

  • This library generates unique-per-request (masked) tokens as a mitigation against the BREACH attack.
  • The 'base' (unmasked) token is stored in the session, which means that multiple browser tabs won't cause a user problems as their per-request token is compared with the base token.
  • Operates on a "whitelist only" approach where safe (non-mutating) HTTP methods (GET, HEAD, OPTIONS, TRACE) are the only methods where token validation is not enforced.
  • The design is based on the battle-tested Django and Ruby on Rails approaches.
  • Cookies are authenticated and based on the securecookie library. They're also Secure (issued over HTTPS only) and are HttpOnly by default, because sane defaults are important.
  • Cookie SameSite attribute (prevents cookies from being sent by a browser during cross site requests) are not set by default to maintain backwards compatibility for legacy systems. The SameSite attribute can be set with the SameSite option.
  • Go's crypto/rand library is used to generate the 32 byte (256 bit) tokens and the one-time-pad used for masking them.

This library does not seek to be adventurous.

License

BSD licensed. See the LICENSE file for details.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].