-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
184 lines (144 loc) · 4.29 KB
/
middleware.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
package auth
import (
"context"
"crypto/rsa"
"encoding/json"
"go-graphql-mongo-server/common"
"go-graphql-mongo-server/config"
"go-graphql-mongo-server/logger"
"go-graphql-mongo-server/models"
"io"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v5"
)
type OIDCInfo struct {
JwksURI string `json:"jwks_uri"`
}
type PublicKey struct {
Kty string `json:"kty"`
Kid string `json:"kid"`
E string `json:"e"`
N string `json:"n"`
Use string `json:"use"`
Key rsa.PublicKey
}
var oidcInfo OIDCInfo
var publicKeysMap = make(map[string]PublicKey)
func retrieveFromURL(url string) ([]byte, error) {
req, _ := http.NewRequest(http.MethodGet, url, nil)
httpClient := common.GetHTTPClient(true)
resp, err := httpClient.Do(req)
if err != nil {
logger.Log.Errorf("Error in retrieving OIDC info: %v", err)
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
logger.Log.Errorf("Error in reading OIDC info: %v", err)
return nil, err
}
return body, nil
}
func RefreshOIDCInfo() {
if !config.Store.Auth.OidcEnabled {
return
}
body, err := retrieveFromURL(config.Store.Auth.OidcURL + "/.well-known/openid-configuration")
if err != nil {
logger.Log.Errorf("Error in retrieving OIDC info: %v", err)
return
}
err = json.Unmarshal(body, &oidcInfo)
if err != nil {
logger.Log.Errorf("Error in parsing OIDC configuration info: %v", err)
return
}
jwksURLBody, err := retrieveFromURL(oidcInfo.JwksURI)
if err != nil {
logger.Log.Errorf("Error in retrieving OIDC public keys: %v", err)
return
}
var publicKeys struct {
Keys []PublicKey `json:"keys"`
}
err = json.Unmarshal(jwksURLBody, &publicKeys)
if err != nil {
logger.Log.Errorf("Error in parsing OIDC public keys: %v", err)
return
}
if len(publicKeys.Keys) == 0 {
logger.Log.Info("No OIDC public keys found")
return
}
// Clear the old publicKeysMap
publicKeysMap = make(map[string]PublicKey)
for _, key := range publicKeys.Keys {
if key.Use == "sig" && key.Kty == "RSA" {
key.Key, err = generateRSAPublicKey(key.N, key.E)
if err != nil {
logger.Log.Errorf("Error in generating RSA public key: %v", err)
} else {
publicKeysMap[key.Kid] = key
}
}
}
logger.Log.Info("Refreshed OIDC info")
}
func Middleware(next http.Handler) http.Handler {
if config.Store.Auth.OidcEnabled && (len(oidcInfo.JwksURI) == 0 || len(publicKeysMap) == 0) {
logger.Log.Info("No OIDC info found")
RefreshOIDCInfo()
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenString := r.Header.Get("Authorization")
tokenString = strings.TrimPrefix(tokenString, "Bearer ")
if tokenString == "" {
//Guest User
//To allow the user to access the protected routes, comment the following line
common.RespondWithUnauthorized(w)
// To stop the user from accessing the protected routes, comment the following line
// r = setUserNameInReq(r, models.GuestUser)
// next.ServeHTTP(w, r)
} else if tokenString == config.Store.SecretToken {
//Internal User (Eg. Other backend services)
r = setUserNameInReq(r, models.InternalUser)
next.ServeHTTP(w, r)
} else {
//Validate Token
validateToken(tokenString, next, w, r)
}
})
}
func setUserNameInReq(r *http.Request, userName string) *http.Request {
return r.WithContext(context.WithValue(r.Context(), models.UserContextKey, userName))
}
func validateToken(tokenString string, next http.Handler, w http.ResponseWriter, r *http.Request) {
token, err := parseToken(r.Context(), tokenString)
if err != nil {
logger.Log.Error("Error while parsing token")
common.RespondWithUnauthorized(w)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if ok && token.Valid && claims["sub"] != nil {
r = setUserNameInReq(r, claims["sub"].(string))
next.ServeHTTP(w, r)
} else {
common.RespondWithJSON(w, http.StatusUnauthorized, map[string]string{"message": "Unauthorized"})
}
}
func parseToken(ctx context.Context, tokenString string) (*jwt.Token, error) {
parsedToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (pubKey interface{}, err error) {
if config.Store.Auth.OidcEnabled {
pubKey, err = validateOIDCToken(ctx, token, tokenString)
if err == nil {
return
}
}
pubKey, err = validateJwtInHouse(ctx, token, tokenString)
return
})
return parsedToken, err
}