{"id":13366427,"url":"https://github.com/Gorilla/csrf","last_synced_at":"2025-03-12T18:30:58.774Z","repository":{"id":35815094,"uuid":"40097643","full_name":"gorilla/csrf","owner":"gorilla","description":"Package gorilla/csrf provides Cross Site Request Forgery (CSRF) prevention middleware for Go web applications \u0026 services 🔒","archived":false,"fork":false,"pushed_at":"2024-03-04T22:20:13.000Z","size":147,"stargazers_count":1045,"open_issues_count":7,"forks_count":155,"subscribers_count":27,"default_branch":"main","last_synced_at":"2024-10-15T05:40:56.627Z","etag":null,"topics":["csrf","csrf-protection","csrf-tokens","go","golang","gorilla","gorilla-web-toolkit","middleware","security","xsrf"],"latest_commit_sha":null,"homepage":"https://gorilla.github.io","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gorilla.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-08-03T00:35:16.000Z","updated_at":"2024-10-15T01:42:01.000Z","dependencies_parsed_at":"2023-01-16T06:57:38.495Z","dependency_job_id":"72c4528c-d536-4c09-bf88-049824ee3af5","html_url":"https://github.com/gorilla/csrf","commit_stats":{"total_commits":87,"total_committers":29,"mean_commits":3.0,"dds":0.3793103448275862,"last_synced_commit":"a009743572494ccbc9d159005bdc58b86a44ddba"},"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gorilla%2Fcsrf","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gorilla%2Fcsrf/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gorilla%2Fcsrf/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gorilla%2Fcsrf/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gorilla","download_url":"https://codeload.github.com/gorilla/csrf/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":221309821,"owners_count":16795817,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csrf","csrf-protection","csrf-tokens","go","golang","gorilla","gorilla-web-toolkit","middleware","security","xsrf"],"created_at":"2024-07-30T00:01:24.647Z","updated_at":"2024-10-24T11:30:16.691Z","avatar_url":"https://github.com/gorilla.png","language":"Go","readme":"# gorilla/csrf\n\n![testing](https://github.com/gorilla/csrf/actions/workflows/test.yml/badge.svg)\n[![codecov](https://codecov.io/github/gorilla/csrf/branch/main/graph/badge.svg)](https://codecov.io/github/gorilla/csrf)\n[![godoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf)\n[![sourcegraph](https://sourcegraph.com/github.com/gorilla/csrf/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/csrf?badge)\n\n\n![Gorilla Logo](https://github.com/gorilla/.github/assets/53367916/d92caabf-98e0-473e-bfbf-ab554ba435e5)\n\ngorilla/csrf is a HTTP middleware library that provides [cross-site request\nforgery](http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/) (CSRF)\nprotection. It includes:\n\n- The `csrf.Protect` middleware/handler provides CSRF protection on routes\n  attached to a router or a sub-router.\n- A `csrf.Token` function that provides the token to pass into your response,\n  whether that be a HTML form or a JSON response body.\n- ... and a `csrf.TemplateField` helper that you can pass into your `html/template`\n  templates to replace a `{{ .csrfField }}` template tag with a hidden input\n  field.\n\ngorilla/csrf is designed to work with any Go web framework, including:\n\n- The [Gorilla](https://www.gorillatoolkit.org/) toolkit\n- Go's built-in [net/http](http://golang.org/pkg/net/http/) package\n- [Goji](https://goji.io) - see the [tailored fork](https://github.com/goji/csrf)\n- [Gin](https://github.com/gin-gonic/gin)\n- [Echo](https://github.com/labstack/echo)\n- ... and any other router/framework that rallies around Go's `http.Handler` interface.\n\ngorilla/csrf is also compatible with middleware 'helper' libraries like\n[Alice](https://github.com/justinas/alice) and [Negroni](https://github.com/codegangsta/negroni).\n\n## Contents\n\n  * [Install](#install)\n  * [Examples](#examples)\n    + [HTML Forms](#html-forms)\n    + [JavaScript Applications](#javascript-applications)\n    + [Google App Engine](#google-app-engine)\n    + [Setting SameSite](#setting-samesite)\n    + [Setting Options](#setting-options)\n  * [Design Notes](#design-notes)\n  * [License](#license)\n\n## Install\n\nWith a properly configured Go toolchain:\n\n```sh\ngo get github.com/gorilla/csrf\n```\n\n## Examples\n\n- [HTML Forms](#html-forms)\n- [JavaScript Apps](#javascript-applications)\n- [Google App Engine](#google-app-engine)\n- [Setting SameSite](#setting-samesite)\n- [Setting Options](#setting-options)\n\ngorilla/csrf is easy to use: add the middleware to your router with\nthe below:\n\n```go\nCSRF := csrf.Protect([]byte(\"32-byte-long-auth-key\"))\nhttp.ListenAndServe(\":8000\", CSRF(r))\n```\n\n...and then collect the token with `csrf.Token(r)` in your handlers before\npassing it to the template, JSON body or HTTP header (see below).\n\nNote that the authentication key passed to `csrf.Protect([]byte(key))` should:\n- be 32-bytes long\n- persist across application restarts.\n- kept secret from potential malicious users - do not hardcode it into the source code, especially not in open-source applications.\n\nGenerating a random key won't allow you to authenticate existing cookies and will break your CSRF\nvalidation.\n\ngorilla/csrf inspects the HTTP headers (first) and form body (second) on\nsubsequent POST/PUT/PATCH/DELETE/etc. requests for the token.\n\n### HTML Forms\n\nHere's the common use-case: HTML forms you want to provide CSRF protection for,\nin order to protect malicious POST requests being made:\n\n```go\npackage main\n\nimport (\n    \"net/http\"\n\n    \"github.com/gorilla/csrf\"\n    \"github.com/gorilla/mux\"\n)\n\nfunc main() {\n    r := mux.NewRouter()\n    r.HandleFunc(\"/signup\", ShowSignupForm)\n    // All POST requests without a valid token will return HTTP 403 Forbidden.\n    // We should also ensure that our mutating (non-idempotent) handler only\n    // matches on POST requests. We can check that here, at the router level, or\n    // within the handler itself via r.Method.\n    r.HandleFunc(\"/signup/post\", SubmitSignupForm).Methods(\"POST\")\n\n    // Add the middleware to your router by wrapping it.\n    http.ListenAndServe(\":8000\",\n        csrf.Protect([]byte(\"32-byte-long-auth-key\"))(r))\n    // PS: Don't forget to pass csrf.Secure(false) if you're developing locally\n    // over plain HTTP (just don't leave it on in production).\n}\n\nfunc ShowSignupForm(w http.ResponseWriter, r *http.Request) {\n    // signup_form.tmpl just needs a {{ .csrfField }} template tag for\n    // csrf.TemplateField to inject the CSRF token into. Easy!\n    t.ExecuteTemplate(w, \"signup_form.tmpl\", map[string]interface{}{\n        csrf.TemplateTag: csrf.TemplateField(r),\n    })\n    // We could also retrieve the token directly from csrf.Token(r) and\n    // set it in the request header - w.Header.Set(\"X-CSRF-Token\", token)\n    // This is useful if you're sending JSON to clients or a front-end JavaScript\n    // framework.\n}\n\nfunc SubmitSignupForm(w http.ResponseWriter, r *http.Request) {\n    // We can trust that requests making it this far have satisfied\n    // our CSRF protection requirements.\n}\n```\n\nNote that the CSRF middleware will (by necessity) consume the request body if the\ntoken is passed via POST form values. If you need to consume this in your\nhandler, insert your own middleware earlier in the chain to capture the request\nbody.\n\n### JavaScript Applications\n\nThis approach is useful if you're using a front-end JavaScript framework like\nReact, Ember or Angular, and are providing a JSON API. Specifically, we need\nto provide a way for our front-end fetch/AJAX calls to pass the token on each\nfetch (AJAX/XMLHttpRequest) request. We achieve this by:\n\n- Parsing the token from the `\u003cinput\u003e` field generated by the\n  `csrf.TemplateField(r)` helper, or passing it back in a response header.\n- Sending this token back on every request\n- Ensuring our cookie is attached to the request so that the form/header\n  value can be compared to the cookie value.\n\nWe'll also look at applying selective CSRF protection using\n[gorilla/mux's](https://www.gorillatoolkit.org/pkg/mux) sub-routers,\nas we don't handle any POST/PUT/DELETE requests with our top-level router.\n\n```go\npackage main\n\nimport (\n    \"github.com/gorilla/csrf\"\n    \"github.com/gorilla/mux\"\n)\n\nfunc main() {\n    r := mux.NewRouter()\n    csrfMiddleware := csrf.Protect([]byte(\"32-byte-long-auth-key\"))\n\n    api := r.PathPrefix(\"/api\").Subrouter()\n    api.Use(csrfMiddleware)\n    api.HandleFunc(\"/user/{id}\", GetUser).Methods(\"GET\")\n\n    http.ListenAndServe(\":8000\", r)\n}\n\nfunc GetUser(w http.ResponseWriter, r *http.Request) {\n    // Authenticate the request, get the id from the route params,\n    // and fetch the user from the DB, etc.\n\n    // Get the token and pass it in the CSRF header. Our JSON-speaking client\n    // or JavaScript framework can now read the header and return the token in\n    // in its own \"X-CSRF-Token\" request header on the subsequent POST.\n    w.Header().Set(\"X-CSRF-Token\", csrf.Token(r))\n    b, err := json.Marshal(user)\n    if err != nil {\n        http.Error(w, err.Error(), 500)\n        return\n    }\n\n    w.Write(b)\n}\n```\n\nIn our JavaScript application, we should read the token from the response\nheaders and pass it in a request header for all requests. Here's what that\nlooks like when using [Axios](https://github.com/axios/axios), a popular\nJavaScript HTTP client library:\n\n```js\n// You can alternatively parse the response header for the X-CSRF-Token, and\n// store that instead, if you followed the steps above to write the token to a\n// response header.\nlet csrfToken = document.getElementsByName(\"gorilla.csrf.Token\")[0].value\n\n// via https://github.com/axios/axios#creating-an-instance\nconst instance = axios.create({\n  baseURL: \"https://example.com/api/\",\n  timeout: 1000,\n  headers: { \"X-CSRF-Token\": csrfToken }\n})\n\n// Now, any HTTP request you make will include the csrfToken from the page,\n// provided you update the csrfToken variable for each render.\ntry {\n  let resp = await instance.post(endpoint, formData)\n  // Do something with resp\n} catch (err) {\n  // Handle the exception\n}\n```\n\nIf you plan to host your JavaScript application on another domain, you can use the Trusted Origins\nfeature to allow the host of your JavaScript application to make requests to your Go application. Observe the example below:\n\n\n```go\npackage main\n\nimport (\n    \"github.com/gorilla/csrf\"\n    \"github.com/gorilla/mux\"\n)\n\nfunc main() {\n    r := mux.NewRouter()\n    csrfMiddleware := csrf.Protect([]byte(\"32-byte-long-auth-key\"), csrf.TrustedOrigins([]string{\"ui.domain.com\"}))\n\n    api := r.PathPrefix(\"/api\").Subrouter()\n    api.Use(csrfMiddleware)\n    api.HandleFunc(\"/user/{id}\", GetUser).Methods(\"GET\")\n\n    http.ListenAndServe(\":8000\", r)\n}\n\nfunc GetUser(w http.ResponseWriter, r *http.Request) {\n    // Authenticate the request, get the id from the route params,\n    // and fetch the user from the DB, etc.\n\n    // Get the token and pass it in the CSRF header. Our JSON-speaking client\n    // or JavaScript framework can now read the header and return the token in\n    // in its own \"X-CSRF-Token\" request header on the subsequent POST.\n    w.Header().Set(\"X-CSRF-Token\", csrf.Token(r))\n    b, err := json.Marshal(user)\n    if err != nil {\n        http.Error(w, err.Error(), 500)\n        return\n    }\n\n    w.Write(b)\n}\n```\n\nOn 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.\n\n### Google App Engine\n\nIf you're using [Google App\nEngine](https://cloud.google.com/appengine/docs/go/how-requests-are-handled#Go_Requests_and_HTTP),\n(first-generation) which doesn't allow you to hook into the default `http.ServeMux` directly,\nyou can still use gorilla/csrf (and gorilla/mux):\n\n```go\npackage app\n\n// Remember: appengine has its own package main\nfunc init() {\n    r := mux.NewRouter()\n    r.HandleFunc(\"/\", IndexHandler)\n    // ...\n\n    // We pass our CSRF-protected router to the DefaultServeMux\n    http.Handle(\"/\", csrf.Protect([]byte(your-key))(r))\n}\n```\n\nNote: You can ignore this if you're using the\n[second-generation](https://cloud.google.com/appengine/docs/go/) Go runtime\non App Engine (Go 1.11 and above).\n\n### Setting SameSite\n\nGo 1.11 introduced the option to set the SameSite attribute in cookies. This is\nvaluable if a developer wants to instruct a browser to not include cookies during\na cross site request. SameSiteStrictMode prevents all cross site requests from including\nthe cookie. SameSiteLaxMode prevents CSRF prone requests (POST) from including the cookie\nbut allows the cookie to be included in GET requests to support external linking.\n\n```go\nfunc main() {\n    CSRF := csrf.Protect(\n      []byte(\"a-32-byte-long-key-goes-here\"),\n      // instruct the browser to never send cookies during cross site requests\n      csrf.SameSite(csrf.SameSiteStrictMode),\n    )\n\n    r := mux.NewRouter()\n    r.HandleFunc(\"/signup\", GetSignupForm)\n    r.HandleFunc(\"/signup/post\", PostSignupForm)\n\n    http.ListenAndServe(\":8000\", CSRF(r))\n}\n```\n\n### Cookie path\n\nBy default, CSRF cookies are set on the path of the request.\n\nThis can create issues, if the request is done from one path to a different path.\n\nYou might want to set up a root path for all the cookies; that way, the CSRF will always work across all your paths.\n\n```\n    CSRF := csrf.Protect(\n      []byte(\"a-32-byte-long-key-goes-here\"),\n      csrf.Path(\"/\"),\n    )\n```\n\n### Setting Options\n\nWhat about providing your own error handler and changing the HTTP header the\npackage inspects on requests? (i.e. an existing API you're porting to Go). Well,\ngorilla/csrf provides options for changing these as you see fit:\n\n```go\nfunc main() {\n    CSRF := csrf.Protect(\n            []byte(\"a-32-byte-long-key-goes-here\"),\n            csrf.RequestHeader(\"Authenticity-Token\"),\n            csrf.FieldName(\"authenticity_token\"),\n            csrf.ErrorHandler(http.HandlerFunc(serverError(403))),\n    )\n\n    r := mux.NewRouter()\n    r.HandleFunc(\"/signup\", GetSignupForm)\n    r.HandleFunc(\"/signup/post\", PostSignupForm)\n\n    http.ListenAndServe(\":8000\", CSRF(r))\n}\n```\n\nNot too bad, right?\n\nIf there's something you're confused about or a feature you would like to see\nadded, open an issue.\n\n## Design Notes\n\nGetting CSRF protection right is important, so here's some background:\n\n- This library generates unique-per-request (masked) tokens as a mitigation\n  against the [BREACH attack](http://breachattack.com/).\n- The 'base' (unmasked) token is stored in the session, which means that\n  multiple browser tabs won't cause a user problems as their per-request token\n  is compared with the base token.\n- Operates on a \"whitelist only\" approach where safe (non-mutating) HTTP methods\n  (GET, HEAD, OPTIONS, TRACE) are the _only_ methods where token validation is not\n  enforced.\n- The design is based on the battle-tested\n  [Django](https://docs.djangoproject.com/en/1.8/ref/csrf/) and [Ruby on\n  Rails](http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html)\n  approaches.\n- Cookies are authenticated and based on the [securecookie](https://github.com/gorilla/securecookie)\n  library. They're also Secure (issued over HTTPS only) and are HttpOnly\n  by default, because sane defaults are important.\n- Cookie SameSite attribute (prevents cookies from being sent by a browser\n  during cross site requests) are not set by default to maintain backwards compatibility\n  for legacy systems. The SameSite attribute can be set with the SameSite option.\n- Go's `crypto/rand` library is used to generate the 32 byte (256 bit) tokens\n  and the one-time-pad used for masking them.\n\nThis library does not seek to be adventurous.\n\n## License\n\nBSD licensed. See the LICENSE file for details.\n","funding_links":[],"categories":["表单","表單"],"sub_categories":["高级控制台界面","高級控制台界面"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGorilla%2Fcsrf","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FGorilla%2Fcsrf","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGorilla%2Fcsrf/lists"}