...

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

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

     1  package main
     2  
     3  import (
     4  	"log"
     5  	"time"
     6  
     7  	"github.com/golang-jwt/jwt/v4"
     8  
     9  	"github.com/MicahParks/keyfunc"
    10  )
    11  
    12  func main() {
    13  	// Get the JWKS URL.
    14  	//
    15  	// This is a sample JWKS service. Visit https://jwks-service.appspot.com/ and grab a token to test this example.
    16  	jwksURL := "https://jwks-service.appspot.com/.well-known/jwks.json"
    17  
    18  	// Create the keyfunc options. Use an error handler that logs. Refresh the JWKS every hour. Timeout the JWKS refresh
    19  	// request after 10 seconds. This timeout is also used to create the initial context.Context for keyfunc.Get.
    20  	options := keyfunc.Options{
    21  		RefreshInterval: time.Hour,
    22  		RefreshTimeout:  time.Second * 10,
    23  		RefreshErrorHandler: func(err error) {
    24  			log.Printf("There was an error with the jwt.Keyfunc\nError: %s", err.Error())
    25  		},
    26  	}
    27  
    28  	// Create the JWKS from the resource at the given URL.
    29  	jwks, err := keyfunc.Get(jwksURL, options)
    30  	if err != nil {
    31  		log.Fatalf("Failed to create JWKS from resource at the given URL.\nError: %s", err.Error())
    32  	}
    33  
    34  	// Get a JWT to parse.
    35  	jwtB64 := "eyJraWQiOiJlZThkNjI2ZCIsInR5cCI6IkpXVCIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiJXZWlkb25nIiwiYXVkIjoiVGFzaHVhbiIsImlzcyI6Imp3a3Mtc2VydmljZS5hcHBzcG90LmNvbSIsImlhdCI6MTYzMTM2OTk1NSwianRpIjoiNDY2M2E5MTAtZWU2MC00NzcwLTgxNjktY2I3NDdiMDljZjU0In0.LwD65d5h6U_2Xco81EClMa_1WIW4xXZl8o4b7WzY_7OgPD2tNlByxvGDzP7bKYA9Gj--1mi4Q4li4CAnKJkaHRYB17baC0H5P9lKMPuA6AnChTzLafY6yf-YadA7DmakCtIl7FNcFQQL2DXmh6gS9J6TluFoCIXj83MqETbDWpL28o3XAD_05UP8VLQzH2XzyqWKi97mOuvz-GsDp9mhBYQUgN3csNXt2v2l-bUPWe19SftNej0cxddyGu06tXUtaS6K0oe0TTbaqc3hmfEiu5G0J8U6ztTUMwXkBvaknE640NPgMQJqBaey0E4u0txYgyvMvvxfwtcOrDRYqYPBnA"
    36  
    37  	// Parse the JWT.
    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  	// End the background refresh goroutine when it's no longer needed.
    50  	jwks.EndBackground()
    51  }
    52  

View as plain text