Skip to content
This repository has been archived by the owner on Feb 8, 2023. It is now read-only.

alibaba-archive/gear-csrf

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

gear-csrf

Build Status Coverage Status License GoDoc

CSRF middleware for Gear.

Installation

go get -u github.com/teambition/gear-csrf

Usage

package main

import (
  "net/http"
  "time"

  "github.com/teambition/gear"
  csrf "github.com/teambition/gear-csrf"
)

func main() {
  app := gear.New()
  router := gear.NewRouter()
  CSRF := csrf.New("some_key", time.Minute*10)

  // http://127.0.0.1:3000/csrf
  router.Get("/csrf", func(ctx *gear.Context) error {
    secret := CSRF.SecretFromCookie(ctx)
    return ctx.JSON(http.StatusOK, map[string]string{
      "secret": secret,
      "token":  CSRF.SignToken(secret),
    })
  })

  // Enable the CSRF checking.
  // http://127.0.0.1:3000/verify-csrf?csrf_token={token}
  router.Get("/verify-csrf", CSRF.Serve, func(ctx *gear.Context) error {
    secret := CSRF.SecretFromCookie(ctx)
    return ctx.JSON(http.StatusOK, map[string]string{
      "secret": secret,
      "verify": "ok",
    })
  })

  app.UseHandler(router)
  app.Listen(":3000")
}

How it works

gear-csrf uses a CSRF token to prevent the CSRF attack. A CSRF token is generated by a user secret and a salt. The user secret is shared by the user's client and the web server by cookie and then you should ensure every way to get the CSRF token in your web server application should not support CORS. So the attacker will not be able to get your CSRF token by his user secret. The salt here is used to prevent BREACH attack.

Documentation

The docs can be found at godoc.org, as usual.

License

MIT