-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add changes for authenticating requests with bearer token
- Loading branch information
Showing
7 changed files
with
170 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package auth | ||
|
||
import ( | ||
"log" | ||
"net/http" | ||
) | ||
|
||
func HandleJwtAuthMiddleware() func(http.Handler) http.Handler { | ||
set, err := getJWKSet("http://localhost:8900/realms/yt-clone/protocol/openid-connect/certs") | ||
if err != nil { | ||
log.Printf("Error fetching jwk-sets: %v\n", err) | ||
} | ||
|
||
return jwtMiddleware(set) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
package auth | ||
|
||
import ( | ||
"crypto/rsa" | ||
"encoding/base64" | ||
"encoding/json" | ||
"fmt" | ||
"io" | ||
"log" | ||
"math/big" | ||
"net/http" | ||
"strings" | ||
) | ||
|
||
func getJWKSet(url string) (map[string]*rsa.PublicKey, error) { | ||
// Make the GET request | ||
response, err := http.Get(url) | ||
if err != nil { | ||
return nil, fmt.Errorf("error making GET request: %v", err) | ||
} | ||
defer func(Body io.ReadCloser) { | ||
err := Body.Close() | ||
if err != nil { | ||
log.Println("Error closing body:", err) | ||
} | ||
}(response.Body) | ||
|
||
// Decode the JSON response | ||
var jwkSet struct { | ||
Keys []struct { | ||
Kid string `json:"kid"` | ||
Alg string `json:"alg"` | ||
N string `json:"n"` | ||
E string `json:"e"` | ||
X5C []string `json:"x5c"` | ||
} `json:"keys"` | ||
} | ||
decoder := json.NewDecoder(response.Body) | ||
if err := decoder.Decode(&jwkSet); err != nil { | ||
return nil, fmt.Errorf("error decoding JSON: %v", err) | ||
} | ||
|
||
// Create a map to store RSA public keys | ||
jwkMap := make(map[string]*rsa.PublicKey) | ||
|
||
// Iterate through each key in the JWK set | ||
for _, key := range jwkSet.Keys { | ||
// Decode base64url-encoded modulus (N) and exponent (E) | ||
modulus, err := decodeBase64URL(key.N) | ||
if err != nil { | ||
return nil, fmt.Errorf("error decoding modulus: %v", err) | ||
} | ||
|
||
exponent, err := decodeBase64URL(key.E) | ||
if err != nil { | ||
return nil, fmt.Errorf("error decoding exponent: %v", err) | ||
} | ||
|
||
// Create RSA public key | ||
pubKey := &rsa.PublicKey{ | ||
N: modulus, | ||
E: int(exponent.Int64()), | ||
} | ||
|
||
// Store the public key in the map using the key ID (Kid) | ||
jwkMap[key.Alg] = pubKey | ||
} | ||
|
||
return jwkMap, nil | ||
} | ||
|
||
func decodeBase64URL(input string) (*big.Int, error) { | ||
base64Str := strings.ReplaceAll(input, "-", "+") | ||
base64Str = strings.ReplaceAll(base64Str, "_", "/") | ||
|
||
switch len(base64Str) % 4 { | ||
case 2: | ||
base64Str += "==" | ||
case 3: | ||
base64Str += "=" | ||
} | ||
|
||
data, err := base64.StdEncoding.DecodeString(base64Str) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
result := new(big.Int).SetBytes(data) | ||
return result, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package auth | ||
|
||
import ( | ||
"crypto/rsa" | ||
"fmt" | ||
"github.com/golang-jwt/jwt/v5" | ||
"log" | ||
"net/http" | ||
"strings" | ||
) | ||
|
||
func jwtMiddleware(jwkSet map[string]*rsa.PublicKey) func(http.Handler) http.Handler { | ||
return func(next http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
authHeader := r.Header.Get("Authorization") | ||
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") { | ||
http.Error(w, "Authorization header is required", http.StatusUnauthorized) | ||
return | ||
} | ||
|
||
tokenString := strings.TrimPrefix(authHeader, "Bearer ") | ||
token, err := jwt.Parse(tokenString, parseToken(jwkSet)) | ||
|
||
if err != nil || !token.Valid { | ||
log.Println("error validating token:", err) | ||
http.Error(w, "", http.StatusUnauthorized) | ||
return | ||
} | ||
|
||
issuer, err := token.Claims.GetIssuer() | ||
if err != nil || issuer != "http://localhost:8900/realms/yt-clone" { | ||
log.Println("error validating issuer:", err) | ||
http.Error(w, "", http.StatusUnauthorized) | ||
return | ||
} | ||
|
||
next.ServeHTTP(w, r) | ||
}) | ||
} | ||
} | ||
|
||
func parseToken(jwkSet map[string]*rsa.PublicKey) func(token *jwt.Token) (interface{}, error) { | ||
return func(token *jwt.Token) (interface{}, error) { | ||
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { | ||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) | ||
} | ||
|
||
alg := token.Method.Alg() | ||
publicKey, ok := jwkSet[alg] | ||
if !ok { | ||
return nil, fmt.Errorf("no key found for signing method: %v", alg) | ||
} | ||
return publicKey, nil | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters