-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt-claims.go
88 lines (74 loc) · 2.5 KB
/
jwt-claims.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
83
84
85
86
87
88
package traefik_jwt_claims
import (
"context"
"fmt"
"github.com/golang-jwt/jwt/v5"
"net/http"
"strings"
)
type Config struct {
SecretKey string `json:"secretKey,omitempty"`
NameOfAuthorizationHeader string `json:"nameOfAuthorizationHeader,omitempty"`
NameOfUserIDInToken string `json:"nameOfUserIDInToken,omitempty"`
NameForUserIDInHeader string `json:"nameForUserIDInHeader,omitempty"`
ExcludePaths string `json:"excludePaths,omitempty"`
}
func CreateConfig() *Config {
return &Config{}
}
type TraefikJWTClaims struct {
next http.Handler
name string
SecretKey string
NameOfAuthorizationHeader string
NameOfUserIDInToken string
NameForUserIDInHeader string
ExcludePaths map[string]struct{}
}
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
return &TraefikJWTClaims{
next: next,
name: name,
SecretKey: config.SecretKey,
NameOfAuthorizationHeader: config.NameOfAuthorizationHeader,
NameOfUserIDInToken: config.NameOfUserIDInToken,
NameForUserIDInHeader: config.NameForUserIDInHeader,
ExcludePaths: func() map[string]struct{} {
paths := make(map[string]struct{})
for _, path := range strings.Split(config.ExcludePaths, ",") {
paths[path] = struct{}{}
}
return paths
}(),
}, nil
}
func (t *TraefikJWTClaims) ServeHTTP(resp http.ResponseWriter, request *http.Request) {
if t.pathShouldNotUseAuthentication(request.URL.Path) {
t.next.ServeHTTP(resp, request)
return
}
token, err := t.getToken(request.Header.Get(t.NameOfAuthorizationHeader))
if err != nil || token == nil || !token.Valid {
resp.WriteHeader(http.StatusUnauthorized)
return
}
claims := token.Claims.(jwt.MapClaims)
request.Header.Set(t.NameForUserIDInHeader, claims[t.NameOfUserIDInToken].(string))
t.next.ServeHTTP(resp, request)
}
func (t *TraefikJWTClaims) getToken(stringToken string) (*jwt.Token, error) {
token, err := jwt.Parse(stringToken, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("método de assinatura inválido: %v", token.Header["alg"])
}
return []byte(t.SecretKey), nil
})
return token, err
}
func (t *TraefikJWTClaims) pathShouldNotUseAuthentication(path string) bool {
if strings.Contains(path, "swagger") {
return true
}
_, ok := t.ExcludePaths[path]
return ok
}