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.")
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?