✨ Support build jwk from jwt reader
This commit is contained in:
parent
73a8d11c7e
commit
25ab137173
@ -3,9 +3,11 @@ package sec
|
|||||||
import (
|
import (
|
||||||
"crypto/rsa"
|
"crypto/rsa"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
|
"encoding/base64"
|
||||||
"encoding/pem"
|
"encoding/pem"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/golang-jwt/jwt/v5"
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
"math/big"
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -40,8 +42,8 @@ func NewJwtReader(fp string) (*JwtReader, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ReadJwt is the helper method to help me validate and parse jwt.
|
// ReadJwt is the helper method to help me validate and parse jwt.
|
||||||
// To use it, pass the initialized jwt reader which contains public key.
|
// 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
|
// 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) {
|
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) {
|
token, err := jwt.ParseWithClaims(in, out, func(token *jwt.Token) (interface{}, error) {
|
||||||
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
|
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
|
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))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user