-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
withJWT.go
232 lines (186 loc) · 5.4 KB
/
withJWT.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
227
228
229
230
231
232
package http
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/LerianStudio/midaz/common/mlog"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt"
"github.com/lestrrat-go/jwx/jwk"
"github.com/patrickmn/go-cache"
)
const (
jwkDefaultDuration = time.Hour * 1
superOrgScope = "*"
)
// TokenContextValue is a wrapper type used to keep Context.Locals safe.
type TokenContextValue string
// ProfileID is the profileID type of a member.
type ProfileID string
// OAuth2JWTToken represents a self-contained way for securely transmitting information between parties as a JSON object
// https://tools.ietf.org/html/rfc7519
type OAuth2JWTToken struct {
Token *jwt.Token
Claims jwt.MapClaims
Groups []string
Sub string
Username *string
Scope string
ScopeSet map[string]bool
}
// TokenFromContext extracts a JWT token from context.
func TokenFromContext(c *fiber.Ctx) (*OAuth2JWTToken, error) {
if tokenValue := c.Locals(string(TokenContextValue("token"))); tokenValue != nil {
if token, ok := tokenValue.(*jwt.Token); ok {
if claims, ok := token.Claims.(jwt.MapClaims); ok {
t := &OAuth2JWTToken{
Token: token,
Claims: claims,
Sub: claims["sub"].(string),
}
if username, found := claims["username"].(string); found {
t.Username = &username
}
if scope, found := claims["scope"].(string); found {
t.Scope = scope
t.ScopeSet = make(map[string]bool)
for _, s := range strings.Split(scope, " ") {
t.ScopeSet[s] = true
}
}
if groups, found := claims["cognito:groups"].([]any); found {
t.Groups = convertGroups(groups)
}
return t, nil
}
}
}
return nil, errors.New("invalid JWT token")
}
func convertGroups(groups []any) []string {
newGroups := make([]string, 0)
for _, g := range groups {
if v, ok := g.(string); ok {
newGroups = append(newGroups, v)
}
}
return newGroups
}
func getTokenHeader(c *fiber.Ctx) string {
splitToken := strings.Split(c.Get(fiber.HeaderAuthorization), "Bearer")
if len(splitToken) == 2 {
return strings.TrimSpace(splitToken[1])
}
return ""
}
// JWKProvider manages cryptographic public keys issued by an authorization server
// See https://tools.ietf.org/html/rfc7517
// It's used to verify JSON Web Tokens which was signed using RS256 signing algorithm.
type JWKProvider struct {
URI string
CacheDuration time.Duration
cache *cache.Cache
once sync.Once
}
// Fetch fetches (JWKS) JSON Web Key Set from authorization server and cache it
//
//nolint:ireturn
func (p *JWKProvider) Fetch(ctx context.Context) (jwk.Set, error) {
p.once.Do(func() {
p.cache = cache.New(p.CacheDuration, p.CacheDuration)
})
if set, found := p.cache.Get(p.URI); found {
return set.(jwk.Set), nil
}
set, err := jwk.Fetch(ctx, p.URI)
if err != nil {
return nil, err
}
p.cache.Set(p.URI, set, p.CacheDuration)
return set, nil
}
// JWTMiddleware represents a middleware which protects endpoint using JWT tokens.
type JWTMiddleware struct {
JWK *JWKProvider
}
// NewJWTMiddleware create an instance of JWTMiddleware
// It uses JWK cache duration of 1 hour.
func NewJWTMiddleware(jwkURI string) *JWTMiddleware {
return &JWTMiddleware{
JWK: &JWKProvider{
URI: jwkURI,
CacheDuration: jwkDefaultDuration,
},
}
}
// Protect protects any endpoint using JWT tokens.
func (m *JWTMiddleware) Protect() fiber.Handler {
return func(c *fiber.Ctx) error {
l := mlog.NewLoggerFromContext(c.UserContext())
l.Debug("JWTMiddleware:Protect")
l.Debug("Read token from header")
tokenString := getTokenHeader(c)
if len(tokenString) == 0 {
return Unauthorized(c, "INVALID_REQUEST", "Must provide a token")
}
// TODO: Need to be cached
l.Debugf("Get JWK keys using %s", m.JWK.URI)
keySet, err := m.JWK.Fetch(context.Background())
if err != nil {
msg := fmt.Sprint("Couldn't now load JWK keys from source: ", err.Error())
l.Error(msg)
return InternalServerError(c, msg)
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
kid, ok := token.Header["kid"].(string)
if !ok {
return nil, errors.New("kid header not found")
}
key, ok := keySet.LookupKeyID(kid)
if !ok {
return nil, errors.New("the provided token doesn't belongs to the required trusted issuer, check the identity server you logged in")
}
var raw any
if err := key.Raw(&raw); err != nil {
return nil, err
}
return raw, nil
})
if err != nil {
l.Error(err.Error())
return Unauthorized(c, "AUTH_SERVER_ERROR", err.Error())
}
if token.Valid {
l.Debug("Token ok")
c.Locals(string(TokenContextValue("token")), token)
return c.Next()
}
return Unauthorized(c, "INVALID_TOKEN", "Invalid token")
}
}
// WithScope verify if a requester has the required scope to access an endpoint.
func (m *JWTMiddleware) WithScope(scopes []string) fiber.Handler {
return func(c *fiber.Ctx) error {
t, err := TokenFromContext(c)
if err != nil {
return Unauthorized(c, "INVALID_SCOPE", "Unauthorized")
}
authorized := false
for _, s := range scopes {
if _, found := t.ScopeSet[s]; found {
authorized = true
break
}
}
if authorized || len(scopes) == 0 {
return c.Next()
}
return Forbidden(c, "Insufficient privileges")
}
}