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