GoWeb/security/csrf.go

55 lines
1.1 KiB
Go
Raw Permalink Normal View History

2022-11-14 18:03:51 +00:00
package security
import (
"crypto/rand"
"encoding/hex"
"log"
"math"
"net/http"
)
// GenerateCsrfToken generates a csrf token and assigns it to a cookie for double submit cookie csrf protection
2022-12-05 00:04:24 +00:00
func GenerateCsrfToken(w http.ResponseWriter, _ *http.Request) (string, error) {
2022-11-14 18:03:51 +00:00
// Generate random 64 character string (alpha-numeric)
buff := make([]byte, int(math.Ceil(float64(64)/2)))
_, err := rand.Read(buff)
if err != nil {
log.Println("Error creating random buffer for csrf token value")
2022-11-14 18:03:51 +00:00
log.Println(err)
return "", err
}
str := hex.EncodeToString(buff)
token := str[:64]
cookie := &http.Cookie{
Name: "csrf_token",
2022-11-14 18:03:51 +00:00
Value: token,
Path: "/",
MaxAge: 1800,
HttpOnly: true,
Secure: true,
}
http.SetCookie(w, cookie)
return token, nil
}
// VerifyCsrfToken verifies the csrf token
func VerifyCsrfToken(r *http.Request) (bool, error) {
cookie, err := r.Cookie("csrf_token")
2022-11-14 18:03:51 +00:00
if err != nil {
log.Println("Error getting csrf_token cookie")
2022-11-14 18:03:51 +00:00
log.Println(err)
return false, err
}
token := r.FormValue("csrf_token")
2022-11-14 18:03:51 +00:00
if cookie.Value == token {
return true, nil
}
return false, nil
}