-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthmiddleware.go
48 lines (40 loc) · 959 Bytes
/
authmiddleware.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
package main
import (
"crypto/subtle"
"log/slog"
"net/http"
"strings"
)
// bearerAuthMiddleware .
type bearerAuthMiddleware struct {
h http.Handler
Token string
}
func (b bearerAuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if b.Token == "" {
slog.Error("auth key not set")
w.WriteHeader(http.StatusUnauthorized)
return
}
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
ss := strings.SplitN(authHeader, " ", 2)
if !(len(ss) == 2 && ss[0] == "Bearer") {
w.WriteHeader(http.StatusUnauthorized)
return
}
if subtle.ConstantTimeCompare([]byte(ss[1]), []byte(b.Token)) == 0 {
w.WriteHeader(http.StatusUnauthorized)
return
}
b.h.ServeHTTP(w, r)
}
func BearerAuthMiddleware(token string) func(h http.Handler) http.Handler {
fn := func(h http.Handler) http.Handler {
return bearerAuthMiddleware{h: h, Token: token}
}
return fn
}