...

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

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

     1  package main
     2  
     3  import (
     4  	"log"
     5  
     6  	"github.com/golang-jwt/jwt/v4"
     7  
     8  	"github.com/MicahParks/keyfunc"
     9  	"github.com/MicahParks/keyfunc/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.CustomAlg, 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),
    33  	})
    34  
    35  	// Parse the token.
    36  	token, err := jwt.Parse(jwtB64, jwks.Keyfunc)
    37  	if err != nil {
    38  		log.Fatalf("Failed to parse the JWT.\nError: %s", err.Error())
    39  	}
    40  
    41  	// Check if the token is valid.
    42  	if !token.Valid {
    43  		log.Fatalf("The token is not valid.")
    44  	}
    45  	log.Println("The token is valid.")
    46  }
    47  

View as plain text