Управление JWT токенами
Relevant source files
The following files were used as context for generating this wiki page:
The JWT token management system in this project provides a secure mechanism for user authentication and authorization. It utilizes a dual-token approach: short-lived Access Tokens for authorizing API requests and long-lived Refresh Tokens for obtaining new token pairs without requiring the user to re-enter credentials.
The system is built using the golang-jwt/jwt/v5 library and integrates with a PostgreSQL database to persist refresh tokens, enabling features like token rotation and global logout.
Sources: internal/features/auth/service/login.go, internal/core/middleware/middleware.go, internal/features/auth/repository/postgres/refresh_token_repository.go
Token Architecture and Data Structures
Token Claims
The system defines a Claims structure that is embedded within the Access Token. These claims carry user identity and authorization metadata, allowing the backend to identify the user and their permissions without querying the database for every request.
| Field | Type | Description |
|---|---|---|
user_id | int64 | Unique identifier of the user |
email | string | User's email address |
role | string | Authorization role (e.g., USER, ADMIN) |
subscription_type | string | User's current subscription level |
RegisteredClaims | struct | Standard JWT claims (ExpiresAt, IssuedAt, etc.) |
Sources: internal/core/middleware/middleware.go:18-24
Database Schema
Refresh tokens are stored in the refresh_tokens table to manage session state and rotation.
The diagram above shows the relationship between users and their refresh tokens.
Sources: migrations/001_init.up.sql:1-20
Token Lifecycle Management
Authentication and Token Generation
Upon a successful login, the AuthService generates both an Access Token (signed with HS256) and a cryptographically secure Refresh Token. The Refresh Token is an opaque hex string generated from random bytes.
The flow shows the generation of tokens during the login process.
Sources: internal/features/auth/service/login.go:31-77
Token Rotation (Refresh)
The system implements Refresh Token Rotation. When a user requests a new Access Token using a Refresh Token, the old Refresh Token is deleted from the database, and a brand-new pair is issued. This mitigates the risk of stolen refresh tokens.
- Validation: Verify the provided token exists in the database and has not expired.
- Revocation: Delete the used Refresh Token from the
refresh_tokenstable. - Issuance: Generate a new Access Token and a new Refresh Token.
- Persistence: Save the new Refresh Token to the database.
Sources: internal/features/auth/service/refresh.go:14-63, internal/features/auth/repository/postgres/refresh_token_repository.go:34-49
Configuration Parameters
The token durations and secrets are managed via environment variables.
| Parameter | Environment Variable | Default Value |
|---|---|---|
| Access Secret | JWT_ACCESS_SECRET | "super_access_secret_key_change_me" |
| Access TTL | JWT_ACCESS_TTL | 15 minutes |
| Refresh TTL | JWT_REFRESH_TTL | 720 hours (30 days) |
Sources: internal/core/config/config.go:39-44
Security Middlewares
AuthMiddleware
This middleware intercepts incoming HTTP requests to validate the Authorization: Bearer <token> header. It parses the JWT, verifies the signature using the configured secret, and injects the Claims into the request context.
func AuthMiddleware(secret string) func(http.Handler) http.Handler {
// ... logic to extract header, parse JWT, and validate claims
}
Sources: internal/core/middleware/middleware.go:119-152
Role-Based Access Control (RBAC)
The RequireRole middleware ensures that only users with specific roles (extracted from the JWT claims) can access certain endpoints, such as admin management tools.
Sources: internal/core/middleware/middleware.go:154-167
Conclusion
The JWT management system ensures a balance between security and user experience. By utilizing short-lived Access Tokens and a Refresh Token rotation strategy backed by PostgreSQL, the service protects user sessions while allowing for secure, long-running authentication states. All token parameters are highly configurable, allowing the system to adapt to different security requirements.