Created
October 21, 2024 10:04
-
-
Save ekkinox/790ae9881dba9386082ba8e5cbbe6122 to your computer and use it in GitHub Desktop.
JWX
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
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"os" | |
"time" | |
"github.com/lestrrat-go/jwx/v2/jwa" | |
"github.com/lestrrat-go/jwx/v2/jwk" | |
"github.com/lestrrat-go/jwx/v2/jwt" | |
) | |
func main() { | |
// KEYS | |
rawKey, err := os.ReadFile("RSA_1024.private") | |
if err != nil { | |
panic(err) | |
} | |
key, err := jwk.ParseKey(rawKey, jwk.WithPEM(true)) | |
if err != nil { | |
panic(err) | |
} | |
err = key.Set(jwk.KeyIDKey, "key-1024") | |
err = key.Set(jwk.AlgorithmKey, jwa.RS256) | |
err = key.Set(jwk.KeyUsageKey, jwk.ForSignature) | |
err = key.Set(jwk.KeyOpsKey, jwk.KeyOperationList{jwk.KeyOpSign, jwk.KeyOpVerify}) | |
if err != nil { | |
panic(err) | |
} | |
// JWKS | |
set := jwk.NewSet() | |
pKey, err := key.PublicKey() | |
err = set.AddKey(pKey) | |
if err != nil { | |
panic(err) | |
} | |
_, ok := set.LookupKeyID("key-1024") | |
if !ok { | |
panic("key-1024 not found") | |
} | |
fmt.Println("JWKS") | |
json.NewEncoder(os.Stdout).Encode(set) | |
fmt.Println() | |
// JWT sign | |
token := jwt.New() | |
token.Set(jwt.SubjectKey, `some-user`) | |
token.Set(jwt.AudienceKey, `Users`) | |
token.Set(jwt.IssuedAtKey, time.Now().Unix()) | |
//token.Set(jwt.ExpirationKey, time.Now().Add(-time.Hour).Unix()) | |
fmt.Printf("alg: %s\n", key.Algorithm().String()) | |
//signedToken, err := jwt.Sign(token, jwt.WithKey(jwa.RS256, key)) | |
signedToken, err := jwt.Sign(token, jwt.WithKey(jwa.SignatureAlgorithm(key.Algorithm().String()), key)) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("JWT sign") | |
fmt.Printf("token: %s", signedToken) | |
fmt.Println() | |
// JWT validate + verify + parse | |
parsedToken, err := jwt.Parse( | |
signedToken, | |
jwt.WithValidate(true), | |
jwt.WithVerify(true), | |
jwt.WithKey(jwa.RS256, pKey), | |
) | |
if err != nil { | |
panic(err) | |
} | |
out, err := json.MarshalIndent(parsedToken, "", " ") | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("JWT parse") | |
fmt.Printf("%s\n", out) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment