Debian Codegraph @

README.md

raw
1 # gorilla/csrf
2
3 ![testing](https://github.com/gorilla/csrf/actions/workflows/test.yml/badge.svg)
4 [![codecov](https://codecov.io/github/gorilla/csrf/branch/main/graph/badge.svg)](https://codecov.io/github/gorilla/csrf)
5 [![godoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf)
6 [![sourcegraph](https://sourcegraph.com/github.com/gorilla/csrf/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/csrf?badge)
7
8
9 ![Gorilla Logo](https://github.com/gorilla/.github/assets/53367916/d92caabf-98e0-473e-bfbf-ab554ba435e5)
10
11 gorilla/csrf is a HTTP middleware library that provides [cross-site request
12 forgery](http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/) (CSRF)
13 protection. It includes:
14
15 - The `csrf.Protect` middleware/handler provides CSRF protection on routes
16 attached to a router or a sub-router.
17 - A `csrf.Token` function that provides the token to pass into your response,
18 whether that be a HTML form or a JSON response body.
19 - ... and a `csrf.TemplateField` helper that you can pass into your `html/template`
20 templates to replace a `{{ .csrfField }}` template tag with a hidden input
21 field.
22
23 gorilla/csrf is designed to work with any Go web framework, including:
24
25 - The [Gorilla](https://www.gorillatoolkit.org/) toolkit
26 - Go's built-in [net/http](http://golang.org/pkg/net/http/) package
27 - [Goji](https://goji.io) - see the [tailored fork](https://github.com/goji/csrf)
28 - [Gin](https://github.com/gin-gonic/gin)
29 - [Echo](https://github.com/labstack/echo)
30 - ... and any other router/framework that rallies around Go's `http.Handler` interface.
31
32 gorilla/csrf is also compatible with middleware 'helper' libraries like
33 [Alice](https://github.com/justinas/alice) and [Negroni](https://github.com/codegangsta/negroni).
34
35 ## Contents
36
37 * [Install](#install)
38 * [Examples](#examples)
39 + [HTML Forms](#html-forms)
40 + [JavaScript Applications](#javascript-applications)
41 + [Google App Engine](#google-app-engine)
42 + [Setting SameSite](#setting-samesite)
43 + [Setting Options](#setting-options)
44 * [Design Notes](#design-notes)
45 * [License](#license)
46
47 ## Install
48
49 With a properly configured Go toolchain:
50
51 ```sh
52 go get github.com/gorilla/csrf
53 ```
54
55 ## Examples
56
57 - [HTML Forms](#html-forms)
58 - [JavaScript Apps](#javascript-applications)
59 - [Google App Engine](#google-app-engine)
60 - [Setting SameSite](#setting-samesite)
61 - [Setting Options](#setting-options)
62
63 gorilla/csrf is easy to use: add the middleware to your router with
64 the below:
65
66 ```go
67 CSRF := csrf.Protect([]byte("32-byte-long-auth-key"))
68 http.ListenAndServe(":8000", CSRF(r))
69 ```
70
71 ...and then collect the token with `csrf.Token(r)` in your handlers before
72 passing it to the template, JSON body or HTTP header (see below).
73
74 Note that the authentication key passed to `csrf.Protect([]byte(key))` should:
75 - be 32-bytes long
76 - persist across application restarts.
77 - kept secret from potential malicious users - do not hardcode it into the source code, especially not in open-source applications.
78
79 Generating a random key won't allow you to authenticate existing cookies and will break your CSRF
80 validation.
81
82 gorilla/csrf inspects the HTTP headers (first) and form body (second) on
83 subsequent POST/PUT/PATCH/DELETE/etc. requests for the token.
84
85 ### HTML Forms
86
87 Here's the common use-case: HTML forms you want to provide CSRF protection for,
88 in order to protect malicious POST requests being made:
89
90 ```go
91 package main
92
93 import (
94 "net/http"
95
96 "github.com/gorilla/csrf"
97 "github.com/gorilla/mux"
98 )
99
100 func main() {
101 r := mux.NewRouter()
102 r.HandleFunc("/signup", ShowSignupForm)
103 // All POST requests without a valid token will return HTTP 403 Forbidden.
104 // We should also ensure that our mutating (non-idempotent) handler only
105 // matches on POST requests. We can check that here, at the router level, or
106 // within the handler itself via r.Method.
107 r.HandleFunc("/signup/post", SubmitSignupForm).Methods("POST")
108
109 // Add the middleware to your router by wrapping it.
110 http.ListenAndServe(":8000",
111 csrf.Protect([]byte("32-byte-long-auth-key"))(r))
112 // PS: Don't forget to pass csrf.Secure(false) if you're developing locally
113 // over plain HTTP (just don't leave it on in production).
114 }
115
116 func ShowSignupForm(w http.ResponseWriter, r *http.Request) {
117 // signup_form.tmpl just needs a {{ .csrfField }} template tag for
118 // csrf.TemplateField to inject the CSRF token into. Easy!
119 t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{
120 csrf.TemplateTag: csrf.TemplateField(r),
121 })
122 // We could also retrieve the token directly from csrf.Token(r) and
123 // set it in the request header - w.Header.Set("X-CSRF-Token", token)
124 // This is useful if you're sending JSON to clients or a front-end JavaScript
125 // framework.
126 }
127
128 func SubmitSignupForm(w http.ResponseWriter, r *http.Request) {
129 // We can trust that requests making it this far have satisfied
130 // our CSRF protection requirements.
131 }
132 ```
133
134 Note that the CSRF middleware will (by necessity) consume the request body if the
135 token is passed via POST form values. If you need to consume this in your
136 handler, insert your own middleware earlier in the chain to capture the request
137 body.
138
139 ### JavaScript Applications
140
141 This approach is useful if you're using a front-end JavaScript framework like
142 React, Ember or Angular, and are providing a JSON API. Specifically, we need
143 to provide a way for our front-end fetch/AJAX calls to pass the token on each
144 fetch (AJAX/XMLHttpRequest) request. We achieve this by:
145
146 - Parsing the token from the `<input>` field generated by the
147 `csrf.TemplateField(r)` helper, or passing it back in a response header.
148 - Sending this token back on every request
149 - Ensuring our cookie is attached to the request so that the form/header
150 value can be compared to the cookie value.
151
152 We'll also look at applying selective CSRF protection using
153 [gorilla/mux's](https://www.gorillatoolkit.org/pkg/mux) sub-routers,
154 as we don't handle any POST/PUT/DELETE requests with our top-level router.
155
156 ```go
157 package main
158
159 import (
160 "github.com/gorilla/csrf"
161 "github.com/gorilla/mux"
162 )
163
164 func main() {
165 r := mux.NewRouter()
166 csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"))
167
168 api := r.PathPrefix("/api").Subrouter()
169 api.Use(csrfMiddleware)
170 api.HandleFunc("/user/{id}", GetUser).Methods("GET")
171
172 http.ListenAndServe(":8000", r)
173 }
174
175 func GetUser(w http.ResponseWriter, r *http.Request) {
176 // Authenticate the request, get the id from the route params,
177 // and fetch the user from the DB, etc.
178
179 // Get the token and pass it in the CSRF header. Our JSON-speaking client
180 // or JavaScript framework can now read the header and return the token in
181 // in its own "X-CSRF-Token" request header on the subsequent POST.
182 w.Header().Set("X-CSRF-Token", csrf.Token(r))
183 b, err := json.Marshal(user)
184 if err != nil {
185 http.Error(w, err.Error(), 500)
186 return
187 }
188
189 w.Write(b)
190 }
191 ```
192
193 In our JavaScript application, we should read the token from the response
194 headers and pass it in a request header for all requests. Here's what that
195 looks like when using [Axios](https://github.com/axios/axios), a popular
196 JavaScript HTTP client library:
197
198 ```js
199 // You can alternatively parse the response header for the X-CSRF-Token, and
200 // store that instead, if you followed the steps above to write the token to a
201 // response header.
202 let csrfToken = document.getElementsByName("gorilla.csrf.Token")[0].value
203
204 // via https://github.com/axios/axios#creating-an-instance
205 const instance = axios.create({
206 baseURL: "https://example.com/api/",
207 timeout: 1000,
208 headers: { "X-CSRF-Token": csrfToken }
209 })
210
211 // Now, any HTTP request you make will include the csrfToken from the page,
212 // provided you update the csrfToken variable for each render.
213 try {
214 let resp = await instance.post(endpoint, formData)
215 // Do something with resp
216 } catch (err) {
217 // Handle the exception
218 }
219 ```
220
221 If you plan to host your JavaScript application on another domain, you can use the Trusted Origins
222 feature to allow the host of your JavaScript application to make requests to your Go application. Observe the example below:
223
224
225 ```go
226 package main
227
228 import (
229 "github.com/gorilla/csrf"
230 "github.com/gorilla/mux"
231 )
232
233 func main() {
234 r := mux.NewRouter()
235 csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"), csrf.TrustedOrigins([]string{"ui.domain.com"}))
236
237 api := r.PathPrefix("/api").Subrouter()
238 api.Use(csrfMiddleware)
239 api.HandleFunc("/user/{id}", GetUser).Methods("GET")
240
241 http.ListenAndServe(":8000", r)
242 }
243
244 func GetUser(w http.ResponseWriter, r *http.Request) {
245 // Authenticate the request, get the id from the route params,
246 // and fetch the user from the DB, etc.
247
248 // Get the token and pass it in the CSRF header. Our JSON-speaking client
249 // or JavaScript framework can now read the header and return the token in
250 // in its own "X-CSRF-Token" request header on the subsequent POST.
251 w.Header().Set("X-CSRF-Token", csrf.Token(r))
252 b, err := json.Marshal(user)
253 if err != nil {
254 http.Error(w, err.Error(), 500)
255 return
256 }
257
258 w.Write(b)
259 }
260 ```
261
262 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.
263
264 ### Google App Engine
265
266 If you're using [Google App
267 Engine](https://cloud.google.com/appengine/docs/go/how-requests-are-handled#Go_Requests_and_HTTP),
268 (first-generation) which doesn't allow you to hook into the default `http.ServeMux` directly,
269 you can still use gorilla/csrf (and gorilla/mux):
270
271 ```go
272 package app
273
274 // Remember: appengine has its own package main
275 func init() {
276 r := mux.NewRouter()
277 r.HandleFunc("/", IndexHandler)
278 // ...
279
280 // We pass our CSRF-protected router to the DefaultServeMux
281 http.Handle("/", csrf.Protect([]byte(your-key))(r))
282 }
283 ```
284
285 Note: You can ignore this if you're using the
286 [second-generation](https://cloud.google.com/appengine/docs/go/) Go runtime
287 on App Engine (Go 1.11 and above).
288
289 ### Setting SameSite
290
291 Go 1.11 introduced the option to set the SameSite attribute in cookies. This is
292 valuable if a developer wants to instruct a browser to not include cookies during
293 a cross site request. SameSiteStrictMode prevents all cross site requests from including
294 the cookie. SameSiteLaxMode prevents CSRF prone requests (POST) from including the cookie
295 but allows the cookie to be included in GET requests to support external linking.
296
297 ```go
298 func main() {
299 CSRF := csrf.Protect(
300 []byte("a-32-byte-long-key-goes-here"),
301 // instruct the browser to never send cookies during cross site requests
302 csrf.SameSite(csrf.SameSiteStrictMode),
303 )
304
305 r := mux.NewRouter()
306 r.HandleFunc("/signup", GetSignupForm)
307 r.HandleFunc("/signup/post", PostSignupForm)
308
309 http.ListenAndServe(":8000", CSRF(r))
310 }
311 ```
312
313 ### Cookie path
314
315 By default, CSRF cookies are set on the path of the request.
316
317 This can create issues, if the request is done from one path to a different path.
318
319 You might want to set up a root path for all the cookies; that way, the CSRF will always work across all your paths.
320
321 ```
322 CSRF := csrf.Protect(
323 []byte("a-32-byte-long-key-goes-here"),
324 csrf.Path("/"),
325 )
326 ```
327
328 ### Setting Options
329
330 What about providing your own error handler and changing the HTTP header the
331 package inspects on requests? (i.e. an existing API you're porting to Go). Well,
332 gorilla/csrf provides options for changing these as you see fit:
333
334 ```go
335 func main() {
336 CSRF := csrf.Protect(
337 []byte("a-32-byte-long-key-goes-here"),
338 csrf.RequestHeader("Authenticity-Token"),
339 csrf.FieldName("authenticity_token"),
340 csrf.ErrorHandler(http.HandlerFunc(serverError(403))),
341 )
342
343 r := mux.NewRouter()
344 r.HandleFunc("/signup", GetSignupForm)
345 r.HandleFunc("/signup/post", PostSignupForm)
346
347 http.ListenAndServe(":8000", CSRF(r))
348 }
349 ```
350
351 Not too bad, right?
352
353 If there's something you're confused about or a feature you would like to see
354 added, open an issue.
355
356 ## Design Notes
357
358 Getting CSRF protection right is important, so here's some background:
359
360 - This library generates unique-per-request (masked) tokens as a mitigation
361 against the [BREACH attack](http://breachattack.com/).
362 - The 'base' (unmasked) token is stored in the session, which means that
363 multiple browser tabs won't cause a user problems as their per-request token
364 is compared with the base token.
365 - Operates on a "whitelist only" approach where safe (non-mutating) HTTP methods
366 (GET, HEAD, OPTIONS, TRACE) are the _only_ methods where token validation is not
367 enforced.
368 - The design is based on the battle-tested
369 [Django](https://docs.djangoproject.com/en/1.8/ref/csrf/) and [Ruby on
370 Rails](http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html)
371 approaches.
372 - Cookies are authenticated and based on the [securecookie](https://github.com/gorilla/securecookie)
373 library. They're also Secure (issued over HTTPS only) and are HttpOnly
374 by default, because sane defaults are important.
375 - Cookie SameSite attribute (prevents cookies from being sent by a browser
376 during cross site requests) are not set by default to maintain backwards compatibility
377 for legacy systems. The SameSite attribute can be set with the SameSite option.
378 - Go's `crypto/rand` library is used to generate the 32 byte (256 bit) tokens
379 and the one-time-pad used for masking them.
380
381 This library does not seek to be adventurous.
382
383 ## License
384
385 BSD licensed. See the LICENSE file for details.