-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
82 lines (69 loc) · 2.18 KB
/
auth.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
package main
import (
"context"
"errors"
"net/http"
"slices"
"strings"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
var (
errInvalidAuthorizationHeader = errors.New("invalid Authorization header")
)
type Verifier interface {
Verify(ctx context.Context, rawIDToken string) (*oidc.IDToken, error)
}
// AuthHandler returns a Handler to authenticate requests
func AuthHandler(subjects []string, verifier Verifier) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Trace().Func(func(e *zerolog.Event) {
headers := r.Header.Clone()
headers.Del("Authorization")
if r.Header.Get("Authorization") != "" {
headers.Set("Authorization", "!REMOVED!")
}
e.Interface("headers", headers)
}).Msg("Request details")
t := time.Now()
auth := r.Header.Get("Authorization")
jwt, err := parseAuthHeader(auth)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("Forbidden"))
log.Info().Err(err).Dur("elappsed_ms", time.Since(t)).Int("status", http.StatusUnauthorized).Msg("Unauthorized")
return
}
token, err := verifier.Verify(r.Context(), jwt)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte("Forbidden"))
log.Info().Err(err).Dur("elappsed_ms", time.Since(t)).Int("status", http.StatusUnauthorized).Msg("Unauthorized")
return
}
subject := token.Subject
found := slices.Contains(subjects, subject)
if !found {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte("Forbidden"))
log.Info().Err(err).Dur("elappsed_ms", time.Since(t)).Int("status", http.StatusForbidden).Str("sub", subject).Msg("Forbidden")
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("OK"))
log.Info().Dur("elappsed_ms", time.Since(t)).Int("status", http.StatusOK).Str("sub", subject).Msg("Authorized")
})
}
func parseAuthHeader(authorization string) (string, error) {
auths := strings.Split(authorization, "Bearer ")
if len(auths) != 2 {
return "", errInvalidAuthorizationHeader
}
token := strings.TrimSpace(auths[1])
if len(token) == 0 {
return "", errInvalidAuthorizationHeader
}
return token, nil
}