Skip to content

martinreus/csrf

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CSRF Protection middleware for Go

Build Status

This library implements a very lean CSRF filter for go applications, focused on REST API's.

If you want to protect your backend with a more complete version, which is able to issue CSRF tokens that may be used in HTML rendering in the backend, see https://github.com/gorilla/csrf, which inspired this one.

HOW TO USE

Backend

package main

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

func main() {
    r := mux.NewRouter()
    csrfMiddleware := csrf.CookieCSRF()
    
    // if you want to chage default options of the filter,
    // csrf.CookieCSRF(csrf.Secure(false), csrf.SkipUserAgents("user-service-agent"))

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

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

func GetUser(w http.ResponseWriter, r *http.Request) {...}

func UpdateUser(w http.ResponseWriter, r *http.Request) {...}

Front end

Just read the value received in cookie "XSRF-TOKEN" and send it in a header named "X-XSRF-TOKEN" of a new request.

Hint: nothing needs to be done for Angular apps, as angular already handles this automatically for us ;)

TODO

  • Generate HMAC token instead of purely UUID generated one. This is to prevent clients generating and setting Cookies on the fly. Does not however solve XSS attacks, which still have to be prevented by the front end framework of your choice.

I WANT TO HELP

Yes, please

About

CSRF protection Middleware for golang

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages