How do I generate and verify JWTs in Go?

JSON Web Tokens (JWTs) are a compact, URL-safe means of representing claims to be transferred between two parties. In Go, you can easily generate and verify JWTs using the "github.com/dgrijalva/jwt-go" package. Below is an example demonstrating how to create and validate JWTs in Go.

The following code example shows how to generate and verify a JWT:

package main import ( "fmt" "time" "github.com/dgrijalva/jwt-go" ) func main() { // Generate JWT token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "foo": "bar", "exp": time.Now().Add(time.Hour * 72).Unix(), }) // Sign the token with a secret secret := []byte("your-256-bit-secret") tokenString, err := token.SignedString(secret) if err != nil { fmt.Println("Error signing token:", err) return } fmt.Println("Generated Token:", tokenString) // Verify JWT parsedToken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { // Ensure token method is valid if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } return secret, nil }) if err != nil { fmt.Println("Token is invalid:", err) return } if claims, ok := parsedToken.Claims.(jwt.MapClaims); ok && parsedToken.Valid { fmt.Println("Token is valid. Claims:") fmt.Println(claims) } else { fmt.Println("Token is invalid.") } }

Go JWT JSON Web Tokens Authentication Token Generation Token Verification