...
1 package jwt_test
2
3 import (
4 "fmt"
5 "time"
6
7 "github.com/golang-jwt/jwt"
8 )
9
10
11
12
13
14
15 func ExampleNewWithClaims_standardClaims() {
16 mySigningKey := []byte("AllYourBase")
17
18
19 claims := &jwt.StandardClaims{
20 ExpiresAt: 15000,
21 Issuer: "test",
22 }
23
24 token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
25 ss, err := token.SignedString(mySigningKey)
26 fmt.Printf("%v %v", ss, err)
27
28 }
29
30
31
32 func ExampleNewWithClaims_customClaimsType() {
33 mySigningKey := []byte("AllYourBase")
34
35 type MyCustomClaims struct {
36 Foo string `json:"foo"`
37 jwt.StandardClaims
38 }
39
40
41 claims := MyCustomClaims{
42 "bar",
43 jwt.StandardClaims{
44 ExpiresAt: 15000,
45 Issuer: "test",
46 },
47 }
48
49 token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
50 ss, err := token.SignedString(mySigningKey)
51 fmt.Printf("%v %v", ss, err)
52
53 }
54
55
56
57 func ExampleParseWithClaims_customClaimsType() {
58 tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
59
60 type MyCustomClaims struct {
61 Foo string `json:"foo"`
62 jwt.StandardClaims
63 }
64
65
66 at(time.Unix(0, 0), func() {
67 token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
68 return []byte("AllYourBase"), nil
69 })
70
71 if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
72 fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt)
73 } else {
74 fmt.Println(err)
75 }
76 })
77
78
79 }
80
81
82 func at(t time.Time, f func()) {
83 jwt.TimeFunc = func() time.Time {
84 return t
85 }
86 f()
87 jwt.TimeFunc = time.Now
88 }
89
90
91 func ExampleParse_errorChecking() {
92
93 var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
94
95 token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
96 return []byte("AllYourBase"), nil
97 })
98
99 if token.Valid {
100 fmt.Println("You look nice today")
101 } else if ve, ok := err.(*jwt.ValidationError); ok {
102 if ve.Errors&jwt.ValidationErrorMalformed != 0 {
103 fmt.Println("That's not even a token")
104 } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
105
106 fmt.Println("Timing is everything")
107 } else {
108 fmt.Println("Couldn't handle this token:", err)
109 }
110 } else {
111 fmt.Println("Couldn't handle this token:", err)
112 }
113
114
115 }
116
View as plain text