nonce.go
39 lines1
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
package security
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"log"
"net/http"
"time"
)
type nonceKey struct{}
// NonceFrom returns the per-request nonce, or empty string if none.
func NonceFrom(ctx context.Context) string {
if v, ok := ctx.Value(nonceKey{}).(string); ok {
return v
}
return ""
}
// nonce is the internal middleware that generates a cryptographic nonce per request.
func nonce(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := generateNonce()
ctx := context.WithValue(r.Context(), nonceKey{}, n)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func generateNonce() string {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
log.Printf("crypto/rand failed (fallback nonce): %v", err)
return fmt.Sprintf("%x", time.Now().UnixNano())
}
return base64.StdEncoding.EncodeToString(b)
}