...

Source file src/github.com/golang-jwt/jwt/v5/hmac_example_test.go

Documentation: github.com/golang-jwt/jwt/v5

     1  package jwt_test
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  	"time"
     8  
     9  	"github.com/golang-jwt/jwt/v5"
    10  )
    11  
    12  // For HMAC signing method, the key can be any []byte. It is recommended to generate
    13  // a key using crypto/rand or something equivalent. You need the same key for signing
    14  // and validating.
    15  var hmacSampleSecret []byte
    16  
    17  func init() {
    18  	// Load sample key data
    19  	if keyData, e := os.ReadFile("test/hmacTestKey"); e == nil {
    20  		hmacSampleSecret = keyData
    21  	} else {
    22  		panic(e)
    23  	}
    24  }
    25  
    26  // Example creating, signing, and encoding a JWT token using the HMAC signing method
    27  func ExampleNew_hmac() {
    28  	// Create a new token object, specifying signing method and the claims
    29  	// you would like it to contain.
    30  	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
    31  		"foo": "bar",
    32  		"nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
    33  	})
    34  
    35  	// Sign and get the complete encoded token as a string using the secret
    36  	tokenString, err := token.SignedString(hmacSampleSecret)
    37  
    38  	fmt.Println(tokenString, err)
    39  	// Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU <nil>
    40  }
    41  
    42  // Example parsing and validating a token using the HMAC signing method
    43  func ExampleParse_hmac() {
    44  	// sample token string taken from the New example
    45  	tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU"
    46  
    47  	// Parse takes the token string and a function for looking up the key. The latter is especially
    48  	// useful if you use multiple keys for your application.  The standard is to use 'kid' in the
    49  	// head of the token to identify which key to use, but the parsed token (head and claims) is provided
    50  	// to the callback, providing flexibility.
    51  	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
    52  		// Don't forget to validate the alg is what you expect:
    53  		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
    54  			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
    55  		}
    56  
    57  		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
    58  		return hmacSampleSecret, nil
    59  	})
    60  	if err != nil {
    61  		log.Fatal(err)
    62  	}
    63  
    64  	if claims, ok := token.Claims.(jwt.MapClaims); ok {
    65  		fmt.Println(claims["foo"], claims["nbf"])
    66  	} else {
    67  		fmt.Println(err)
    68  	}
    69  
    70  	// Output: bar 1.4444784e+09
    71  }
    72  

View as plain text