中文文档 | English
JWT (JSON Web Token) is a stateless token solution. The token itself contains user information and expiration time, making it ideal for distributed systems.
- ✅ Stateless: No need for server-side session storage
- ✅ Distributed-friendly: Multiple services can validate independently
- ✅ Self-contained: Token contains user information
- ✅ Cross-domain support: Can be used across different domains
JWT consists of three parts separated by .:
Header.Payload.Signature
Example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbklkIjoiMTAwMCIsImRldmljZSI6IiIsImlhdCI6MTY5NzIzNDU2NywiZXhwIjoxNjk3MjM4MTY3fQ.xxx
import (
"github.com/sa-tokens/sa-token-go/core"
"github.com/sa-tokens/sa-token-go/stputil"
"github.com/sa-tokens/sa-token-go/storage/memory"
)
func init() {
stputil.SetManager(
core.NewBuilder().
Storage(memory.NewStorage()).
TokenStyle(core.TokenStyleJWT). // Use JWT
JwtSecretKey("your-256-bit-secret-key"). // Set secret key
Timeout(3600). // 1 hour
Build(),
)
}// Login and get JWT token
token, _ := stputil.Login(1000)
// Returns: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...// Validate token
if stputil.IsLogin(token) {
fmt.Println("Token is valid")
}
// Get login ID
loginID, _ := stputil.GetLoginID(token)// ❌ Weak key
JwtSecretKey("secret")
// ✅ Strong key (at least 32 bytes recommended)
JwtSecretKey("a-very-long-and-random-secret-key-at-least-256-bits")// Short-term token (recommended)
Timeout(3600) // 1 hour
Timeout(7200) // 2 hours
// Long-term token (needs refresh mechanism)
Timeout(86400) // 24 hoursimport "os"
JwtSecretKey(os.Getenv("JWT_SECRET_KEY"))| Feature | JWT | UUID/Random |
|---|---|---|
| State | Stateless | Stateful |
| Server Storage | Not needed | Required |
| Token Size | Larger | Smaller |
| Revocability | Difficult | Easy |
| Distributed | Excellent | Needs shared storage |
| Performance | High | Medium |