...

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

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

     1  package main
     2  
     3  import (
     4  	"log"
     5  
     6  	"github.com/golang-jwt/jwt/v4"
     7  
     8  	"github.com/MicahParks/keyfunc"
     9  )
    10  
    11  func main() {
    12  	// Declare the custom signing method's key and key ID.
    13  	key := []byte("example secret")
    14  	const exampleKID = "exampleKeyID"
    15  
    16  	// Create and sign the token using the HMAC key.
    17  	unsignedToken := jwt.New(jwt.SigningMethodHS512)
    18  	unsignedToken.Header["kid"] = exampleKID
    19  	jwtB64, err := unsignedToken.SignedString(key)
    20  	if err != nil {
    21  		log.Fatalf("Failed to self sign an HMAC token.\nError: %s.", err.Error())
    22  	}
    23  
    24  	// Create the JWKS from the HMAC key.
    25  	jwks := keyfunc.NewGiven(map[string]keyfunc.GivenKey{
    26  		exampleKID: keyfunc.NewGivenHMAC(key),
    27  	})
    28  
    29  	// Parse the token.
    30  	token, err := jwt.Parse(jwtB64, jwks.Keyfunc)
    31  	if err != nil {
    32  		log.Fatalf("Failed to parse the JWT.\nError: %s", err.Error())
    33  	}
    34  
    35  	// Check if the token is valid.
    36  	if !token.Valid {
    37  		log.Fatalf("The token is not valid.")
    38  	}
    39  	log.Println("The token is valid.")
    40  }
    41  

View as plain text