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