{"id":27400186,"url":"https://github.com/dokadev/jwt_next_client_proto","last_synced_at":"2025-04-14T03:26:40.013Z","repository":{"id":281283957,"uuid":"944810416","full_name":"DokaDev/jwt_next_client_proto","owner":"DokaDev","description":null,"archived":false,"fork":false,"pushed_at":"2025-03-08T02:34:10.000Z","size":0,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-08T03:23:36.259Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DokaDev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-08T02:29:12.000Z","updated_at":"2025-03-08T02:34:13.000Z","dependencies_parsed_at":"2025-03-08T03:23:38.267Z","dependency_job_id":"5064fcd2-03dc-4d47-99d1-1507a8547b13","html_url":"https://github.com/DokaDev/jwt_next_client_proto","commit_stats":null,"previous_names":["dokadev/jwt_next_client_proto"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DokaDev%2Fjwt_next_client_proto","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DokaDev%2Fjwt_next_client_proto/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DokaDev%2Fjwt_next_client_proto/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DokaDev%2Fjwt_next_client_proto/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DokaDev","download_url":"https://codeload.github.com/DokaDev/jwt_next_client_proto/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248814925,"owners_count":21165852,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-04-14T03:26:39.438Z","updated_at":"2025-04-14T03:26:39.996Z","avatar_url":"https://github.com/DokaDev.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# JWT Authentication System Documentation\n\n## Overview\n\nThis document provides a comprehensive explanation of the JWT (JSON Web Token) authentication system implemented in this application. The system is designed to handle user authentication using a combination of AccessToken and RefreshToken, providing secure and efficient API access with automatic token renewal.\n\n## Table of Contents\n1. [Architecture](#architecture)\n2. [Token Management](#token-management)\n3. [Authentication Flow](#authentication-flow)\n4. [Token Renewal Mechanism](#token-renewal-mechanism)\n5. [API Request Handling](#api-request-handling)\n6. [Component Communication](#component-communication)\n7. [Security Considerations](#security-considerations)\n8. [Testing and Debugging](#testing-and-debugging)\n\n## Architecture\n\nThe JWT authentication system follows a layered architecture with clear separation of concerns:\n\n### Core Components:\n\n1. **Auth Utilities (`auth.ts`):**\n   - Responsible for token generation, validation, and decoding\n   - Handles test login and token refresh functionality\n   - Provides utilities for calculating token expiration times\n\n2. **Auth Context (`AuthContext.tsx`):**\n   - Implements React Context for global authentication state management\n   - Manages tokens and user information across the application\n   - Handles periodic token checks and automatic refreshes\n   - Provides authentication hooks for components\n\n3. **API Test Utilities (`apiTest.ts`):**\n   - Simulates API endpoints with varying security requirements\n   - Implements token validation and auto-refresh during API calls\n   - Provides detailed responses with token refresh status\n\n4. **UI Components:**\n   - Authentication buttons for login/logout functionality\n   - API test buttons for demonstrating token usage\n   - Real-time token status display\n\n### Data Flow Diagram:\n\n```\n┌───────────────┐       ┌───────────────┐       ┌───────────────┐\n│               │       │               │       │               │\n│  Auth Utils   │◄─────►│  Auth Context │◄─────►│  UI Components│\n│   (auth.ts)   │       │(AuthContext.tsx)      │(AuthButtons/  │\n│               │       │               │       │ApiTestButtons)│\n└───────┬───────┘       └───────────────┘       └───────────────┘\n        │                                               ▲\n        │                                               │\n        │                      ┌───────────────┐        │\n        └────────────────────►│  API Test     │────────┘\n                              │  (apiTest.ts) │\n                              │               │\n                              └───────────────┘\n```\n\n## Token Management\n\nThe system employs two types of tokens:\n\n### AccessToken:\n- Short-lived (30 seconds in test mode)\n- Used for authenticating API requests\n- Contains user identity and role information\n- Automatically refreshed when nearing expiration\n\n### RefreshToken:\n- Longer-lived (1 minute in test mode)\n- Used only for obtaining new AccessTokens\n- Stored alongside AccessToken\n- Requires re-login when expired\n\n### Token Structure:\nEach JWT token consists of three parts:\n1. **Header:** Contains token type and signing algorithm\n   ```json\n   {\n     \"alg\": \"HS256\",\n     \"typ\": \"JWT\"\n   }\n   ```\n\n2. **Payload:** Contains claims about the user\n   ```json\n   {\n     \"sub\": \"1\",              // User ID\n     \"email\": \"test@example.com\",\n     \"name\": \"Test User\",\n     \"role\": \"user\",\n     \"iat\": 1615480215,       // Issued at timestamp\n     \"exp\": 1615480245        // Expiration timestamp\n   }\n   ```\n\n3. **Signature:** Ensures token integrity (simplified in test implementation)\n\n## Authentication Flow\n\n### Login Process:\n1. User submits credentials (email/password)\n2. `login()` function in AuthContext is called\n3. Credentials are validated against test data\n4. Upon successful authentication:\n   - AccessToken and RefreshToken are generated\n   - Tokens are stored in LocalStorage\n   - User information is extracted from token and stored\n   - AuthContext state is updated, triggering UI re-renders\n   - Timer for token checks is initiated\n\n### Sequence Diagram - Login:\n```\n┌─────┐          ┌─────────────┐          ┌──────────┐          ┌────────────┐\n│ UI  │          │ AuthContext │          │ auth.ts  │          │ LocalStorage│\n└──┬──┘          └──────┬──────┘          └────┬─────┘          └─────┬──────┘\n   │                    │                      │                      │\n   │ login(email, pwd)  │                      │                      │\n   ├───────────────────►│                      │                      │\n   │                    │ loginTest(creds)     │                      │\n   │                    ├─────────────────────►│                      │\n   │                    │                      │                      │\n   │                    │  {user, tokens}      │                      │\n   │                    │◄─────────────────────┤                      │\n   │                    │                      │                      │\n   │                    │ updateTokens()       │                      │\n   │                    ├┐                     │                      │\n   │                    ││ setTokens()         │                      │\n   │                    ││ setUser()           │                      │\n   │                    ││                     │          save tokens │\n   │                    ││                     │                      │\n   │                    │└──────────────────────────────────────────►│\n   │ UI updates         │                      │                      │\n   │◄───────────────────┤                      │                      │\n   │                    │                      │                      │\n```\n\n### Logout Process:\n1. User clicks logout button\n2. `logout()` function in AuthContext is called\n3. User data and tokens are cleared from state\n4. Token data is removed from LocalStorage\n5. UI updates to reflect logged-out state\n\n## Token Renewal Mechanism\n\nThe system includes two complementary token renewal mechanisms:\n\n### 1. Proactive Renewal (Timer-based):\n- A timer runs every 15 seconds to check token status\n- If AccessToken has less than 10 seconds remaining:\n  - RefreshToken is used to obtain new tokens\n  - New tokens replace old ones in state and storage\n  - UI automatically updates to show new expiration times\n\n### 2. Reactive Renewal (API Request-based):\n- When making API requests, token validity is checked\n- If AccessToken is expired but RefreshToken is valid:\n  - New tokens are obtained automatically\n  - Original API request is retried with new token\n  - UI is updated with new token information\n  - Response indicates that tokens were refreshed\n\n### Sequence Diagram - API Call with Token Renewal:\n```\n┌─────┐          ┌───────────┐          ┌──────────┐          ┌────────────┐\n│ UI  │          │ apiTest.ts│          │ auth.ts  │          │AuthContext │\n└──┬──┘          └─────┬─────┘          └────┬─────┘          └─────┬──────┘\n   │ callAPI()         │                      │                      │\n   ├──────────────────►│                      │                      │\n   │                   │ verifyJwt(token)     │                      │\n   │                   ├─────────────────────►│                      │\n   │                   │                      │                      │\n   │                   │ token expired        │                      │\n   │                   │◄─────────────────────┤                      │\n   │                   │                      │                      │\n   │                   │ refreshToken()       │                      │\n   │                   ├─────────────────────►│                      │\n   │                   │                      │                      │\n   │                   │ new tokens           │                      │\n   │                   │◄─────────────────────┤                      │\n   │                   │                      │                      │\n   │                   │ retry API call       │                      │\n   │                   ├┐                     │                      │\n   │                   ││                     │                      │\n   │                   │└────────────────────►│                      │\n   │                   │                      │                      │\n   │                   │ API response         │                      │\n   │                   │◄─────────────────────┤                      │\n   │                   │                      │                      │\n   │ response + tokens │                      │                      │\n   │◄──────────────────┤                      │                      │\n   │                   │                      │                      │\n   │ setTokens()       │                      │                      │\n   ├────────────────────────────────────────────────────────────────►│\n   │                   │                      │                      │\n   │ UI updates        │                      │                      │\n   │◄────────────────────────────────────────────────────────────────┤\n```\n\n## API Request Handling\n\nThe application simulates three types of API endpoints to demonstrate different authentication scenarios:\n\n1. **Public Endpoint:**\n   - No authentication required\n   - Accessible to all users regardless of login status\n   - Always returns success with public data\n\n2. **Protected Endpoint:**\n   - Requires valid AccessToken\n   - Performs token validation before processing\n   - Automatically refreshes token if expired\n   - Returns protected data on success\n\n3. **Admin Endpoint:**\n   - Requires valid AccessToken with admin privileges\n   - Performs both token validation and role-based authorization\n   - Simulates permission checks (randomly succeeds/fails for testing)\n   - Returns admin data on success\n\n### API Request Flow:\n1. Component calls `callTestApi()` with endpoint type and tokens\n2. Function checks if authentication is required for the endpoint\n3. If required, AccessToken is validated\n4. If AccessToken is invalid/expired:\n   - RefreshToken is checked and used if valid\n   - New tokens are obtained and original request is retried\n   - Response includes both API result and token refresh status\n5. Component receives response and updates UI\n6. If tokens were refreshed, AuthContext is updated\n\n## Component Communication\n\nThe system uses React Context API for state management and component communication:\n\n### AuthContext:\n- Provides global authentication state to all components\n- Offers methods for login, logout, and token management\n- Exposes the `useAuth()` hook for components to access auth state\n- Handles token persistence through LocalStorage\n\n### Token State Updates:\n- UI components display real-time token status\n- Token timers update every second, showing remaining validity\n- When tokens change (login, refresh, logout), all components re-render\n- External events triggering token updates (API calls) properly propagate to UI\n\n### External Token Updates:\nWhen API calls result in token refresh, a special mechanism ensures Context state is updated:\n1. API returns refreshed tokens in response\n2. Component receives tokens and calls `setTokens()` from AuthContext\n3. AuthContext updates its state and LocalStorage\n4. All components using the AuthContext re-render with new token information\n\n## Security Considerations\n\nWhile this implementation is primarily for testing and demonstration, it incorporates several security best practices:\n\n### 1. Token Expiration:\n- Short-lived AccessTokens minimize the window for token misuse\n- Automatic refresh mechanism prevents user experience disruption\n\n### 2. Token Validation:\n- Tokens are validated before use in API requests\n- Expired tokens are rejected and refreshed when possible\n\n### 3. Separation of Tokens:\n- AccessToken for regular API requests\n- RefreshToken only used for obtaining new tokens\n\n### 4. Production Recommendations:\n- Use HttpOnly cookies instead of LocalStorage for token storage\n- Implement CSRF protection mechanisms\n- Apply proper HTTPS and secure cookie settings\n- Apply signature verification for tokens\n- Add rate limiting for authentication endpoints\n\n## Testing and Debugging\n\nThe system includes extensive logging and visualization tools for testing and debugging:\n\n### Console Logging:\n- Every authentication action is logged to the console\n- Token generation, validation, and refresh operations are recorded\n- API calls and token checks are documented\n- Timestamps and remaining validity periods are displayed\n\n### UI Visualization:\n- Real-time token status display with countdown timers\n- Color-coded indicators for valid/expired tokens\n- Explicit notification when tokens are refreshed during API calls\n- API response display showing success/failure and data/errors\n\n---\n\nThis implementation provides a complete JWT authentication system with automatic token refresh, emphasizing both security and user experience. While simplified for demonstration, it follows the core principles of proper JWT implementation and can be extended for production use with the recommended security enhancements. ","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdokadev%2Fjwt_next_client_proto","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdokadev%2Fjwt_next_client_proto","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdokadev%2Fjwt_next_client_proto/lists"}