-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
226 lines (200 loc) · 4.98 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
"sync"
"time"
"github.com/go-jose/go-jose/v3"
"github.com/go-jose/go-jose/v3/jwt"
)
// Cache struct
type Cache struct {
sync.RWMutex
jwks *jose.JSONWebKeySet
expires time.Time
}
type CustomClaims struct {
Roles []string `json:"roles,omitempty"`
}
var (
jwksCache = Cache{}
version = "dev"
commit = "none"
date = "unknown"
)
func main() {
log.Printf("VERSION %s, COMMIT %s, BUILD AT %s", version, commit, date)
port := GetPortFromEnv()
jwksUrl := GetJwksURLFromEnv()
authHeaderName := GetAuthHeaderNameFromEnv()
sendAccessTokenBack := GetSendBackAccessTokenEnv()
sendAccessTokenBackName := GetSendBackAccessTokenNameEnv()
sendAllClaimsAsJson := GetSendAllClaimsAsJson()
ttlInSeconds := GetTTLFromEnv()
claimContainsCheck := GetClaimContains()
http.HandleFunc(GetPathFromEnv(), validateToken(
jwksUrl,
authHeaderName,
sendAccessTokenBack,
sendAccessTokenBackName,
ttlInSeconds,
sendAllClaimsAsJson,
claimContainsCheck,
))
http.ListenAndServe(":"+port, nil)
}
func validateToken(
jwksURL string,
authHeaderName string,
sendAccessTokenBack bool,
sendAccessTokenBackName string,
ttlInSeconds int,
sendAllClaimsAsJson bool,
claimContainsCheck []string,
) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
tokenString := extractToken(r, authHeaderName)
if tokenString == "" {
http.Error(w, "No token", http.StatusUnauthorized)
return
}
token, err := jwt.ParseSigned(tokenString)
if err != nil {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
keys, err := getJwksWithCache(jwksURL, ttlInSeconds)
if err != nil {
http.Error(w, "Error fetching JWKS", http.StatusInternalServerError)
return
}
claims := make(map[string]interface{})
for _, key := range keys.Keys {
err = token.Claims(key, &claims)
if err == nil {
if len(claimContainsCheck) > 0 {
if !checkIfClaimContainsAllClaimContainsCheck(claims, claimContainsCheck) {
http.Error(w, "Missing required claims from token", http.StatusUnauthorized)
return
}
}
if sendAccessTokenBack {
w.Header().Set(sendAccessTokenBackName, tokenString)
}
if sendAllClaimsAsJson {
responseJSON, err := json.Marshal(claims)
if err != nil {
http.Error(w, "Failed to marshal JSON", http.StatusInternalServerError)
return
}
_, err = w.Write(responseJSON)
if err != nil {
http.Error(w, "Failed to write JSON", http.StatusInternalServerError)
return
}
} else {
w.Write([]byte("Token valid."))
}
return
}
}
http.Error(w, "Token could not be validated", http.StatusUnauthorized)
}
}
func checkIfClaimContainsAllClaimContainsCheck(claims map[string]interface{}, claimContainsCheck []string) bool {
for _, claimCheck := range claimContainsCheck {
claimCheck = strings.ReplaceAll(claimCheck, "\"", "")
parts := strings.Split(claimCheck, "=")
if len(parts) != 2 {
log.Println("Invalid claim check", claimCheck)
return false
}
key, value := parts[0], parts[1]
claimValue, exists := claims[key]
if !exists {
return false
}
switch v := claimValue.(type) {
case string:
if v != value {
// the string value does not match
return false
}
case []string:
found := false
for _, s := range v {
if s == value {
found = true
break
}
}
if !found {
return false
}
case []interface{}:
found := false
for _, iface := range v {
s, ok := iface.(string)
if !ok {
log.Printf("Unexpected type %T in []interface{} for key %s\n", iface, key)
return false
}
if s == value {
found = true
break
}
}
if !found {
return false
}
default:
log.Printf("Unexpected type %T for key %s\n", v, key)
return false
}
}
return true
}
func extractToken(r *http.Request, authHeaderName string) string {
authHeader := r.Header.Get(authHeaderName)
// often we have bearer token
strArr := strings.Split(authHeader, " ")
if len(strArr) == 2 {
return strArr[1]
} else if len(strArr) == 1 {
return strArr[0]
}
return ""
}
func getJwksWithCache(jwksURL string, ttlInSeconds int) (*jose.JSONWebKeySet, error) {
jwksCache.RLock()
if jwksCache.jwks != nil && time.Now().Before(jwksCache.expires) {
defer jwksCache.RUnlock()
return jwksCache.jwks, nil
}
jwksCache.RUnlock()
jwksCache.Lock()
defer jwksCache.Unlock()
// Double-checked locking
if jwksCache.jwks != nil && time.Now().Before(jwksCache.expires) {
return jwksCache.jwks, nil
}
jwks, err := getJwks(jwksURL)
if err != nil {
return nil, err
}
jwksCache.jwks = jwks
jwksCache.expires = time.Now().Add(time.Duration(ttlInSeconds) * time.Second)
return jwksCache.jwks, nil
}
func getJwks(jwksURL string) (*jose.JSONWebKeySet, error) {
resp, err := http.Get(jwksURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var jwks = new(jose.JSONWebKeySet)
err = json.NewDecoder(resp.Body).Decode(jwks)
return jwks, err
}