-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
78 lines (61 loc) · 1.96 KB
/
http.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
package oidcauth
import (
"net/http"
"strings"
)
// HTTPMiddleware is the middleware for HTTP handler.
type HTTPMiddleware func(http.Handler) http.Handler
// HTTPParams specifies the OIDC authentication settings for HTTP interceptor.
type HTTPParams struct {
Params
// HTTPHeaderName specifies the header name for retrieving the token.
// Defaults to `Authorization`.
HTTPHeaderName string
// HTTPHeaderPrefix specifies the prefix for the header name.
// Defaults to `Bearer`.
HTTPHeaderValuePrefix string
}
func (p HTTPParams) defaults() HTTPParams {
rv := p
rv.Params = p.Params.defaults()
if rv.HTTPHeaderName == "" {
rv.HTTPHeaderName = "Authorization"
}
if rv.HTTPHeaderValuePrefix == "" {
rv.HTTPHeaderValuePrefix = "Bearer"
}
return rv
}
// InterceptHTTP creates a HTTP middleware for authenticating OIDC JWT token
// from the request.
func InterceptHTTP(params HTTPParams) HTTPMiddleware {
params = params.defaults()
loadTokenFromRequest := func(req *http.Request) string {
v := strings.TrimSpace(req.Header.Get(params.HTTPHeaderName))
if v == "" {
return ""
}
v = strings.TrimPrefix(v, params.HTTPHeaderValuePrefix)
v = strings.TrimSpace(v)
return v
}
principalLoader, principalLoaderErr := CreatePrincipalLoader(params.Params)
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var principal ClaimsPrincipal
switch {
case principalLoaderErr != nil:
principal = unauthenticatedClaimsPrincipalWithErr(principalLoaderErr)
default:
principal = principalLoader(r.Context(), loadTokenFromRequest(r))
}
r = r.WithContext(ctxWithClaimsPrincipal(r.Context(), principal))
h.ServeHTTP(w, r)
})
}
}
// PrincipalFromHTTPRequest retrieves the ClaimsPrincipal from the request.
// It returns unauthenticated principal if the request has not set.
func PrincipalFromHTTPRequest(req *http.Request) ClaimsPrincipal {
return claimsPrincipalFromCtx(req.Context())
}