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))), + } +}