GoWeb/security/csrf.go

52 lines
1.1 KiB
Go
Raw Normal View History

2022-11-14 18:03:51 +00:00
package security
import (
"crypto/rand"
"encoding/hex"
"log/slog"
2022-11-14 18:03:51 +00:00
"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
buff := make([]byte, int(math.Ceil(float64(64)/2)))
_, err := rand.Read(buff)
if err != nil {
slog.Error("error creating random buffer for csrf token value" + err.Error())
2022-11-14 18:03:51 +00:00
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 {
slog.Info("unable to get csrf_token cookie" + err.Error())
2022-11-14 18:03:51 +00:00
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
}