TL;DR
Changing a user’s password while they are actively logged in requires careful handling to avoid session invalidation or unexpected behaviour. The best practice is to use a temporary token-based approach, allowing the change to happen without immediately logging the user out. This guide details how to implement this securely.
Steps
- Generate a Unique Token: When the user initiates the password change process (e.g., clicks ‘Change Password’), create a unique, time-limited token.
- This token should be stored server-side associated with the user’s session or account.
- Use a cryptographically secure random number generator for token creation. Example using Python:
import secrets import time token = secrets.token_hex(16) expiry_time = int(time.time()) + 3600 # Token valid for 1 hour # Store token and expiry_time associated with the user - Redirect to Password Change Form: Redirect the user to a dedicated password change form, appending the token as a query parameter.
Example URL:
/change-password?token=your_generated_token - Validate the Token on Form Submission: When the user submits the new password:
- Retrieve the token from the query parameter.
- Check if the token exists in your server-side storage.
- Verify that the token hasn’t expired (compare against
expiry_time). - If the token is invalid or expired, display an error message and prompt the user to restart the password change process.
- Update Password: If the token is valid:
- Hash the new password using a strong hashing algorithm (e.g., bcrypt, Argon2). Never store passwords in plain text!
- Replace the old password hash with the new one in your database.
- Invalidate the Token: Immediately after successfully updating the password, invalidate the token.
This prevents it from being used again.
- Session Management (Important):
- Avoid immediately invalidating the user’s session. This can cause a frustrating experience if they are in the middle of something.
- Consider forcing a re-authentication on the next significant action (e.g., accessing sensitive data) or after a short grace period.
- Security Considerations:
- Token Length: Use sufficiently long tokens to prevent brute-force attacks. 16 bytes (32 hexadecimal characters) is generally considered good.
- HTTPS: Always use HTTPS to protect the token during transmission.
- Rate Limiting: Implement rate limiting on password change requests to mitigate abuse.
- Cross-Site Request Forgery (CSRF): Protect your password change form with CSRF tokens.

