|
| 1 | +package middleware |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/rsa" |
| 6 | + "encoding/base64" |
| 7 | + "encoding/json" |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "math/big" |
| 11 | + "net/http" |
| 12 | + "strings" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/golang-jwt/jwt/v5" |
| 16 | +) |
| 17 | + |
| 18 | +type JWTClaim string |
| 19 | + |
| 20 | +type PublicKeys struct { |
| 21 | + keys map[string]*rsa.PublicKey |
| 22 | +} |
| 23 | + |
| 24 | +type JWKNotFound struct { |
| 25 | +} |
| 26 | + |
| 27 | +func (i JWKNotFound) Error() string { |
| 28 | + return "JWKS Not Found" |
| 29 | +} |
| 30 | + |
| 31 | +func (p *PublicKeys) Get(kid string) *rsa.PublicKey { |
| 32 | + kid = strings.TrimSpace(kid) |
| 33 | + |
| 34 | + return p.keys[kid] |
| 35 | +} |
| 36 | + |
| 37 | +type JWKSProvider interface { |
| 38 | + GetWithHeaders(ctx context.Context, path string, queryParams map[string]interface{}, |
| 39 | + headers map[string]string) (*http.Response, error) |
| 40 | +} |
| 41 | + |
| 42 | +type OauthConfigs struct { |
| 43 | + Provider JWKSProvider |
| 44 | + RefreshInterval time.Duration |
| 45 | +} |
| 46 | + |
| 47 | +func NewOAuth(config OauthConfigs) PublicKeyProvider { |
| 48 | + var publicKeys PublicKeys |
| 49 | + |
| 50 | + publicKeys.keys = make(map[string]*rsa.PublicKey) |
| 51 | + |
| 52 | + go func() { |
| 53 | + for { |
| 54 | + resp, err := config.Provider.GetWithHeaders(context.Background(), "", nil, nil) |
| 55 | + if err != nil || resp == nil { |
| 56 | + continue |
| 57 | + } |
| 58 | + |
| 59 | + body, err := io.ReadAll(resp.Body) |
| 60 | + if err != nil { |
| 61 | + continue |
| 62 | + } |
| 63 | + |
| 64 | + resp.Body.Close() |
| 65 | + |
| 66 | + var jwks JWKS |
| 67 | + |
| 68 | + err = json.Unmarshal(body, &jwks) |
| 69 | + if err != nil { |
| 70 | + continue |
| 71 | + } |
| 72 | + |
| 73 | + publicKeys.keys = publicKeyFromJWKS(jwks) |
| 74 | + |
| 75 | + time.Sleep(config.RefreshInterval) |
| 76 | + } |
| 77 | + }() |
| 78 | + |
| 79 | + return &publicKeys |
| 80 | +} |
| 81 | + |
| 82 | +type PublicKeyProvider interface { |
| 83 | + Get(kid string) *rsa.PublicKey |
| 84 | +} |
| 85 | + |
| 86 | +func OAuth(key PublicKeyProvider) func(inner http.Handler) http.Handler { |
| 87 | + return func(inner http.Handler) http.Handler { |
| 88 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 89 | + authHeader := r.Header.Get("Authorization") |
| 90 | + if authHeader == "" { |
| 91 | + http.Error(w, "Authorization header is required", http.StatusUnauthorized) |
| 92 | + return |
| 93 | + } |
| 94 | + |
| 95 | + headerParts := strings.Split(authHeader, " ") |
| 96 | + if len(headerParts) != 2 || headerParts[0] != "Bearer" { |
| 97 | + http.Error(w, "Authorization header format must be Bearer {token}", http.StatusUnauthorized) |
| 98 | + return |
| 99 | + } |
| 100 | + |
| 101 | + tokenString := headerParts[1] |
| 102 | + |
| 103 | + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { |
| 104 | + kid := token.Header["kid"] |
| 105 | + |
| 106 | + jwks := key.Get(fmt.Sprint(kid)) |
| 107 | + if jwks == nil { |
| 108 | + return nil, JWKNotFound{} |
| 109 | + } |
| 110 | + |
| 111 | + return key.Get(fmt.Sprint(kid)), nil |
| 112 | + }) |
| 113 | + |
| 114 | + if err != nil { |
| 115 | + w.WriteHeader(http.StatusUnauthorized) |
| 116 | + _, _ = w.Write([]byte(err.Error())) |
| 117 | + |
| 118 | + return |
| 119 | + } |
| 120 | + |
| 121 | + ctx := context.WithValue(r.Context(), JWTClaim("JWTClaims"), token.Claims) |
| 122 | + *r = *r.Clone(ctx) |
| 123 | + |
| 124 | + inner.ServeHTTP(w, r) |
| 125 | + }) |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +// JWKS represents a JSON Web Key Set. |
| 130 | +type JWKS struct { |
| 131 | + Keys []JSONWebKey `json:"keys"` |
| 132 | +} |
| 133 | + |
| 134 | +type JSONWebKey struct { |
| 135 | + ID string `json:"kid"` |
| 136 | + Type string `json:"kty"` |
| 137 | + |
| 138 | + Modulus string `json:"n"` |
| 139 | + PublicExponent string `json:"e"` |
| 140 | + PrivateExponent string `json:"d"` |
| 141 | +} |
| 142 | + |
| 143 | +// PublicKeyFromJWKS creates a public key from a JWKS and returns it in string format. |
| 144 | +func publicKeyFromJWKS(jwks JWKS) map[string]*rsa.PublicKey { |
| 145 | + if len(jwks.Keys) == 0 { |
| 146 | + return nil |
| 147 | + } |
| 148 | + |
| 149 | + keys := make(map[string]*rsa.PublicKey) |
| 150 | + |
| 151 | + for _, jwk := range jwks.Keys { |
| 152 | + var val = jwk |
| 153 | + |
| 154 | + keys[jwk.ID], _ = rsaPublicKeyStringFromJWK(&val) |
| 155 | + } |
| 156 | + |
| 157 | + // Store the result of rsaPublicKeyStringFromJWK before the next iteration |
| 158 | + |
| 159 | + return keys |
| 160 | +} |
| 161 | + |
| 162 | +func rsaPublicKeyStringFromJWK(jwk *JSONWebKey) (*rsa.PublicKey, error) { |
| 163 | + n, err := base64.RawURLEncoding.DecodeString(jwk.Modulus) |
| 164 | + if err != nil { |
| 165 | + return nil, err |
| 166 | + } |
| 167 | + |
| 168 | + e, err := base64.RawURLEncoding.DecodeString(jwk.PublicExponent) |
| 169 | + if err != nil { |
| 170 | + return nil, err |
| 171 | + } |
| 172 | + |
| 173 | + nInt := new(big.Int).SetBytes(n) |
| 174 | + eInt := new(big.Int).SetBytes(e) |
| 175 | + |
| 176 | + rsaPublicKey := &rsa.PublicKey{ |
| 177 | + N: nInt, |
| 178 | + E: int(eInt.Int64()), |
| 179 | + } |
| 180 | + |
| 181 | + return rsaPublicKey, nil |
| 182 | +} |
0 commit comments