TL;DR
After a user successfully logs in (database authentication), store a secure token instead of their password. This token is used for future requests, improving security and simplifying session management.
Storing Authentication Tokens After Database Authentication
- Understand the Problem: When a user logs in, you typically verify their credentials against a database. Once verified, you need a way to identify them on subsequent requests without repeatedly asking for their password. Storing passwords directly is dangerous; tokens are much safer.
- Tokens vs Sessions: Tokens are self-contained pieces of information that prove the user’s identity. Sessions store data on the server, linked to a session ID (often stored in a cookie). Tokens offer better scalability and flexibility.
- Choose a Token Type: Several options exist:
- JSON Web Tokens (JWTs): A standard format for securely transmitting information as a JSON object. They are digitally signed, ensuring integrity.
- Randomly Generated Strings: Simpler to implement but require careful management of expiry and revocation.
- Generate the Token on Successful Login: After successful database authentication:
- JWT Example (using a library like PyJWT in Python):
import jwt import datetime secret_key = 'your-secret-key' # Keep this VERY safe! payload = { 'user_id': user.id, 'username': user.username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1) # Token expiry } token = jwt.encode(payload, secret_key, algorithm='HS256') print(token) - Random String Example (Python):
import secrets import string def generate_token(length=32): alphabet = string.ascii_letters + string.digits token = ''.join(secrets.choice(alphabet) for i in range(length)) return token token = generate_token() print(token)
- JWT Example (using a library like PyJWT in Python):
- Store the Token: There are several ways to store the token:
- Client-Side (Cookies): The most common approach. Set an HTTP cookie with the token.
Important: Use
HttpOnlyandSecureflags on cookies for security.HttpOnlyprevents JavaScript access, mitigating XSS attacks.Secureensures the cookie is only sent over HTTPS. - Client-Side (Local Storage/Session Storage): Less secure than cookies due to potential XSS vulnerabilities. Avoid if possible.
- Client-Side (Cookies): The most common approach. Set an HTTP cookie with the token.
- Send the Token with Subsequent Requests: The client must include the token in every subsequent request to protected resources.
- Authorization Header: Use the
Authorizationheader with aBearerscheme:Authorization: Bearer <token>
- Authorization Header: Use the
- Verify the Token on Each Request: On your server, for each protected resource:
- Extract the token from the
Authorizationheader. - JWT Example (Python):
import jwt secret_key = 'your-secret-key' try: data = jwt.decode(token, secret_key, algorithms=['HS256']) user_id = data['user_id'] # Proceed with the request as the authenticated user except jwt.ExpiredSignatureError: # Token has expired return 'Token expired', 401 except jwt.InvalidTokenError: # Invalid token return 'Invalid token', 401 - Random String Example: Check if the token exists in a database of valid tokens (and hasn’t expired).
- Extract the token from the
- Token Expiry and Revocation:
- Expiry: Tokens should have a limited lifespan. This reduces the impact of compromised tokens.
- Revocation: Implement a mechanism to invalidate tokens before their expiry (e.g., when a user logs out or changes their password). This usually involves storing revoked token IDs in a database.

