Documentation
¶
Overview ¶
Package jwt provides JWT signing, verification, and HTTP authentication middleware.
Index ¶
- Variables
- func MustUserID(ctx context.Context) uuid.UUID
- func OptionalAuth(verifier TokenVerifier) func(http.Handler) http.Handler
- func RequireAuth(verifier TokenVerifier) func(http.Handler) http.Handler
- func UserID(ctx context.Context) (uuid.UUID, bool)
- func WithUserID(ctx context.Context, id uuid.UUID) context.Context
- type Config
- type HS256
- type TokenSigner
- type TokenVerifier
- type UserClaims
Constants ¶
This section is empty.
Variables ¶
var ( // ErrTokenExpired indicates that the provided JWT has expired. ErrTokenExpired = errors.New("token is expired") // ErrInvalidToken indicates that the provided JWT is malformed or has an invalid signature. ErrInvalidToken = errors.New("invalid token") // ErrMissingToken indicates that the Authorization header is absent. ErrMissingToken = errors.New("missing authorization header") )
Functions ¶
func MustUserID ¶
MustUserID extracts the user ID from the context or panics if not found.
func OptionalAuth ¶
func OptionalAuth(verifier TokenVerifier) func(http.Handler) http.Handler
OptionalAuth inspects the Authorization header if present. Valid tokens enrich the context, missing headers continue unauthenticated, and invalid tokens return 401 Unauthorized.
func RequireAuth ¶
func RequireAuth(verifier TokenVerifier) func(http.Handler) http.Handler
RequireAuth enforces valid JWT authentication. If the token is missing, expired, or invalid, it responds with 401 Unauthorized via httpx.WriteError.
Types ¶
type Config ¶
type Config struct {
Secret string `toml:"secret" env:"SECRET" env-required:"true" comment:"JWT HMAC-SHA256 secret key"`
Expiration time.Duration `toml:"expiration" env:"EXPIRATION" env-default:"24h" comment:"Access token expiration duration"`
}
Config defines JWT authentication parameters.
type HS256 ¶
type HS256 struct {
// contains filtered or unexported fields
}
HS256 implements TokenSigner and TokenVerifier using HMAC-SHA256.
func (*HS256) SignAccess ¶
SignAccess generates a signed access token for the given user ID.
type TokenSigner ¶
TokenSigner generates signed access tokens for users.
type TokenVerifier ¶
type TokenVerifier interface {
VerifyToken(ctx context.Context, tokenStr string) (uuid.UUID, error)
}
TokenVerifier validates and extracts user identity from access tokens.
type UserClaims ¶
type UserClaims struct {
jwt.RegisteredClaims
UserID string `json:"user_id"`
}
UserClaims defines custom JWT claims including user ID.