...

Source file src/github.com/MicahParks/keyfunc/v2/examples/custom/main.go

Documentation: github.com/MicahParks/keyfunc/v2/examples/custom

     1  package main
     2  
     3  import (
     4  	"log"
     5  
     6  	"github.com/golang-jwt/jwt/v5"
     7  
     8  	"github.com/MicahParks/keyfunc/v2"
     9  	"github.com/MicahParks/keyfunc/v2/examples/custom/method"
    10  )
    11  
    12  func main() {
    13  	// Declare the custom signing method's key and key ID.
    14  	const key = ""
    15  	const exampleKID = "exampleKeyID"
    16  
    17  	// Register the custom signing method.
    18  	jwt.RegisterSigningMethod(method.CustomAlgHeader, func() jwt.SigningMethod {
    19  		return method.EmptyCustom{}
    20  	})
    21  
    22  	// Create and sign the token using the custom signing method.
    23  	unsignedToken := jwt.New(method.EmptyCustom{})
    24  	unsignedToken.Header["kid"] = exampleKID
    25  	jwtB64, err := unsignedToken.SignedString(key)
    26  	if err != nil {
    27  		log.Fatalf("Failed to self sign a custom token.\nError: %s.", err.Error())
    28  	}
    29  
    30  	// Create the JWKS from the given signing method's key.
    31  	jwks := keyfunc.NewGiven(map[string]keyfunc.GivenKey{
    32  		exampleKID: keyfunc.NewGivenCustom(key, keyfunc.GivenKeyOptions{
    33  			Algorithm: method.CustomAlgHeader,
    34  		}),
    35  	})
    36  
    37  	// Parse the token.
    38  	token, err := jwt.Parse(jwtB64, jwks.Keyfunc)
    39  	if err != nil {
    40  		log.Fatalf("Failed to parse the JWT.\nError: %s", err.Error())
    41  	}
    42  
    43  	// Check if the token is valid.
    44  	if !token.Valid {
    45  		log.Fatalf("The token is not valid.")
    46  	}
    47  	log.Println("The token is valid.")
    48  }
    49  

View as plain text