Example parsing and validating a token using the HMAC signing method
()
| 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) (any, error) { |
| 51 | // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key") |
| 52 | return hmacSampleSecret, nil |
| 53 | }, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()})) |
| 54 | if err != nil { |
| 55 | log.Fatal(err) |
| 56 | } |
| 57 | |
| 58 | if claims, ok := token.Claims.(jwt.MapClaims); ok { |
| 59 | fmt.Println(claims["foo"], claims["nbf"]) |
| 60 | } else { |
| 61 | fmt.Println(err) |
| 62 | } |
| 63 | |
| 64 | // Output: bar 1.4444784e+09 |
| 65 | } |