From 25ab1371739b03a5e569a7d32a1b6315fb4aa9b9 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Sat, 23 Nov 2024 13:06:05 +0800 Subject: [PATCH] :sparkles: Support build jwk from jwt reader --- pkg/nex/sec/jwt_reader.go | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/pkg/nex/sec/jwt_reader.go b/pkg/nex/sec/jwt_reader.go index 9963bfe..2584a26 100644 --- a/pkg/nex/sec/jwt_reader.go +++ b/pkg/nex/sec/jwt_reader.go @@ -3,9 +3,11 @@ package sec import ( "crypto/rsa" "crypto/x509" + "encoding/base64" "encoding/pem" "fmt" "github.com/golang-jwt/jwt/v5" + "math/big" "os" ) @@ -40,8 +42,8 @@ func NewJwtReader(fp string) (*JwtReader, error) { } // ReadJwt is the helper method to help me validate and parse jwt. -// To use it, pass the initialized jwt reader which contains public key. -// And pass the token string, and a pointer struct (you must initialize it, which it cannot be nil) of your claims +// To use it, pass the initialized jwt reader which contains a public key. +// And pass the token string and a pointer struct (you must initialize it, which it cannot be nil) of your claims func ReadJwt[T jwt.Claims](v *JwtReader, in string, out T) (T, error) { token, err := jwt.ParseWithClaims(in, out, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { @@ -61,3 +63,18 @@ func ReadJwt[T jwt.Claims](v *JwtReader, in string, out T) (T, error) { return out, err } } + +func (v *JwtReader) BuildJwk(kid string) map[string]any { + encodeBigInt := func(i *big.Int) string { + return base64.RawURLEncoding.EncodeToString(i.Bytes()) + } + + return map[string]any{ + "kid": kid, + "kty": "RSA", + "use": "sig", + "alg": "RS256", + "n": encodeBigInt(v.key.N), + "e": encodeBigInt(big.NewInt(int64(v.key.E))), + } +}