Prerequisites:
Client side password hashing with argon2. (done)
Difference between session id and JWT token:
-
Client should be using and sending session id to server for every request after connecting/reconnecting
- Session id should be generated using the ‘secrets’ python module
- Server stores session ids in database; client only ‘hold’ their won session id, not storing
-
Client should be using a JWT to authenticate themselves only when reconnecting
- JWT token should be generated using the PyJWT package
- Client stores their JWT token on client localStorage; server will verify the token with a secret key or public key
JWT generation instruction
1. Initial Authentication and Token Issuance
- User Sign-in: When a user first signs in (registers or logs in), they provide credentials (username/password) to the server via a secure channel, typically an HTTP request.
- Database Check: The server verifies these credentials against the user records stored in the database. If it's a new user, a new entry is created in the database.
- Token Generation: Upon successful authentication, the server generates a unique, time-limited authentication token, such as a JSON Web Token (JWT), which contains the user's ID and other necessary session information.
- Client Storage: This token is sent back to the client, which stores it securely (e.g., in
localStorage or sessionStorage for web apps).
2. Reconnection and Verification
- Connection Request: When the client loses connection and then attempts to reconnect (often using WebSockets), it includes its stored authentication token in the connection or handshake request.
- Server-Side Validation: The server receives the token and validates its authenticity and expiration. This involves:
- Verifying Signature: Ensuring the token hasn't been tampered with.
- Checking Expiration: Confirming the token is still valid.
- Extracting User ID: Retrieving the unique user ID from the token's payload.
- Database Lookup: Using the extracted user ID, the server performs a database query to confirm the user exists and retrieve their associated data (e.g., username, profile information, message history, current chat rooms).
3. Session Restoration
- Authenticated Session: If the token is valid and the user ID is found in the database, the server accepts the connection and associates the new socket connection with the existing user account.
- Data Synchronization: The server can then send missed messages or the recent chat history to the client, allowing the user to resume their session seamlessly where they left off.