-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsrf.go
96 lines (81 loc) · 1.96 KB
/
csrf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package csrf
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"net/http"
"time"
)
const (
csrfCookieName = "csrf_token"
csrfHeader = "X-CSRF-Token"
)
type CSRF struct {
key []byte
}
func New() *CSRF {
key := make([]byte, 32)
_, err := rand.Read(key)
if err != nil {
panic(err)
}
return &CSRF{key}
}
func (c *CSRF) GenerateToken() string {
token := make([]byte, 32)
_, err := rand.Read(token)
if err != nil {
panic(err)
}
return base64.StdEncoding.EncodeToString(token)
}
func (c *CSRF) SetCookie(w http.ResponseWriter, token string) {
cookie := http.Cookie{
Name: csrfCookieName,
Value: token,
HttpOnly: true,
Path: "/",
Expires: time.Now().Add(time.Hour * 1),
SameSite: http.SameSiteDefaultMode,
}
http.SetCookie(w, &cookie)
}
func (c *CSRF) GetCookie(r *http.Request) string {
cookie, err := r.Cookie(csrfCookieName)
if err != nil {
return ""
}
return cookie.Value
}
func (c *CSRF) VerifyToken(r *http.Request) bool {
token := c.GetCookie(r)
if token == "" {
return false
}
headerToken := r.Header.Get(csrfHeader)
if headerToken == "" {
return false
}
return c.IsValid(token, headerToken)
}
func (c *CSRF) IsValid(token, headerToken string) bool {
return subtle.ConstantTimeCompare([]byte(token), []byte(headerToken)) == 1
}
func (c *CSRF) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// validate CSRF tokens on any HTTP methods that make state-changing requests, such as POST, PUT, PATCH, and DELETE.
if r.Method == http.MethodPost ||
r.Method == http.MethodPut ||
r.Method == http.MethodPatch ||
r.Method == http.MethodDelete {
if c.VerifyToken(r) {
next.ServeHTTP(w, r)
return
}
http.Error(w, "Invalid CSRF token", http.StatusForbidden)
}
// HTTP methods that only retrieve data, such as GET, HEAD, and OPTIONS, do not typically require CSRF token validation
next.ServeHTTP(w, r)
return
})
}