...
1 package jwt_test
2
3 import (
4 "fmt"
5 "io/ioutil"
6 "time"
7
8 "github.com/golang-jwt/jwt"
9 )
10
11
12
13
14 var hmacSampleSecret []byte
15
16 func init() {
17
18 if keyData, e := ioutil.ReadFile("test/hmacTestKey"); e == nil {
19 hmacSampleSecret = keyData
20 } else {
21 panic(e)
22 }
23 }
24
25
26 func ExampleNew_hmac() {
27
28
29 token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
30 "foo": "bar",
31 "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
32 })
33
34
35 tokenString, err := token.SignedString(hmacSampleSecret)
36
37 fmt.Println(tokenString, err)
38
39 }
40
41
42 func ExampleParse_hmac() {
43
44 tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU"
45
46
47
48
49
50 token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
51
52 if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
53 return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
54 }
55
56
57 return hmacSampleSecret, nil
58 })
59
60 if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
61 fmt.Println(claims["foo"], claims["nbf"])
62 } else {
63 fmt.Println(err)
64 }
65
66
67 }
68
View as plain text