top

Package csrf generates and validates csrf tokens for martini. There are multiple methods of delivery including via a cookie or HTTP header. Validation occurs via a traditional hidden form key of "_csrf", or via a custom HTTP header "X-CSRFToken".

package main

import (

"github.com/go-martini/martini"
"github.com/martini-contib/csrf"
"github.com/martini-contrib/render"
"github.com/martini-contib/sessions"
"net/http"

)

func main() {

m := martini.Classic()
store := sessions.NewCookieStore([]byte("secret123"))
m.Use(sessions.Sessions("my_session", store))
// Setup generation middleware.
m.Use(csrf.Generate(&csrf.Options{
    Secret:     "token123",
    SessionKey: "userID",
}))
m.Use(render.Renderer())

// Simulate the authentication of a session. If userID exists redirect
// to a form that requires csrf protection.
m.Get("/", func(s sessions.Session, r render.Render) {
    if s.Get("userID") == nil {
        r.Redirect("/login", 302)
        return
    }
    r.Redirect("/protected", 302)
})

// Set userID for the session.
m.Get("/login", func(s sessions.Session, r render.Render) {
    s.Set("userID", "123456")
    r.Redirect("/", 302)
})

// Render a protected form. Passing a csrf token by calling x.GetToken()
m.Get("/protected", func(s sessions.Session, r render.Render, x csrf.CSRF) {
    if s.Get("userID") == nil {
        r.Redirect("/login", 401)
        return
    }
    r.HTML(200, "protected", x.GetToken())
})

// Apply csrf validation to route.
m.Post("/protected", csrf.Validate, func(s sessions.Session, r render.Render) {
    if s.Get("userID") != nil {
        r.HTML(200, "result", "You submitted a valid token")
        return
    }
    r.Redirect("/login", 401)
})

m.Run()

}

Imports 3 package(s) ΒΆ

  1. github.com/ConradIrwin/xsrftoken
  2. github.com/go-martini/martini
  3. github.com/martini-contrib/sessions