Documentation
¶
Overview ¶
Package jwt provides an instance-based JWT manager using HS256.
The Manager is not a global singleton — each instance holds its own key, issuer, and expiration, making it safe for concurrent use and test isolation.
Index ¶
Constants ¶
const DefaultLeeway = 30 * time.Second
DefaultLeeway is the default exp/iat skew tolerance. Clocks between signer and verifier in distributed deployments commonly drift by hundreds of milliseconds; without leeway, freshly signed tokens can be rejected as "issued in the future". 30 seconds is conservative and covers typical NTP-synced fleets.
const MaxLeeway = 5 * time.Minute
MaxLeeway caps clock-skew tolerance at 5 minutes. Beyond that, Leeway becomes a silent extension of token lifetime — a 24h Leeway on a 2h exp makes expired tokens accepted for a full day. NewManager rejects larger values.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager signs and parses JWT tokens using HS256.
func NewManager ¶
NewManager creates a Manager. Returns an error if SigningKey is empty or shorter than 32 bytes.
func (*Manager) Parse ¶
Parse validates a JWT string and returns the subject and all claims.
Validation rules:
- Only HS256 is accepted (alg=none and other methods are rejected).
- exp must be present and valid (WithExpirationRequired).
- iat must not be in the future (WithIssuedAt).
- iss is validated if Options.Issuer was set.
Parse does not depend on *gin.Context — Bearer extraction is handled by the middleware layer.
Parse satisfies the middleware.TokenParser interface.
type Options ¶
type Options struct {
// SigningKey is required. Must be >= 32 bytes for HS256 security.
// Recommended: generate with `openssl rand -base64 32`, then decode
// before passing (or pass the raw 32+ byte string directly).
// The value is used as-is (raw bytes); no automatic base64 decoding.
SigningKey string
// Issuer is written to the "iss" claim if non-empty. When set, Parse also
// validates the issuer.
Issuer string
// Expiration is the token lifetime. Defaults to 2 hours.
Expiration time.Duration
// Leeway tolerates small clock drift between signer and verifier when
// validating exp / iat / nbf. Defaults to DefaultLeeway (30s). Set
// to a negative value to disable (strict validation).
Leeway time.Duration
// Now returns the current time. Defaults to time.Now.
// Inject a fixed clock in tests to verify expiration without sleeping.
Now func() time.Time
}
Options configures a JWT Manager.