TL;DR
This guide shows you how to use Bearer tokens for secure API access and manage user sessions effectively, protecting against common vulnerabilities. We’ll cover token generation, storage, validation, and session handling best practices.
1. Generate Secure Tokens
Bearer tokens are used to represent an authorization grant. They should be cryptographically signed for security.
- Choose a Library: Use established libraries like PyJWT (Python), jsonwebtoken (Node.js) or similar in your language. Avoid rolling your own cryptography!
- Secret Key: Keep your secret key extremely safe. Store it as an environment variable, not directly in code.
- Token Payload: Include essential information like user ID and expiry time (
expclaim). Don’t put sensitive data here.
# Python example using PyJWT
import jwt
import datetime
secret_key = 'your-super-secret-key'
payload = {'user_id': 123, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}
token = jwt.encode(payload, secret_key, algorithm='HS256')
print(token)
2. Token Storage
How you store the token depends on your application type.
- Client-Side (Web): Use
localStorageorsessionStorage, but be aware of XSS risks. Consider using HTTP-only cookies for better security. - Mobile Apps: Secure storage mechanisms provided by the operating system (e.g., Keychain on iOS, Keystore on Android).
- Server-Side: Store tokens in a secure database or cache with appropriate access controls.
3. Token Validation
Every API request must validate the token before granting access.
- Middleware: Implement middleware to intercept requests and verify the token’s signature, expiry time, and other claims.
- Library Functions: Use your chosen library’s validation functions (e.g.,
jwt.decode()in PyJWT). - Error Handling: Return a 401 Unauthorized error if the token is invalid or expired.
# Python example using PyJWT
try:
decoded_payload = jwt.decode(token, secret_key, algorithms=['HS256'])
user_id = decoded_payload['user_id']
print(f'User ID: {user_id}')
except jwt.ExpiredSignatureError:
print('Token has expired')
except jwt.InvalidTokenError:
print('Invalid token signature')
4. Session Management
Tokens are often used to represent sessions.
- Stateless Sessions: The most common approach. The token itself contains all session information.
- Stateful Sessions (Less Common): Store session data on the server and associate it with a unique session ID. This requires more infrastructure but allows for more complex session management.
5. Refresh Tokens
To avoid frequent logins, use refresh tokens.
- Longer Expiry: Refresh tokens have a longer expiry time than access tokens.
- Secure Storage: Store refresh tokens securely (database is recommended).
- Token Exchange: When an access token expires, the client sends the refresh token to the server to obtain a new access token.
- Revocation: Implement a mechanism to revoke refresh tokens if necessary (e.g., user logout or security breach).
6. Security Considerations
- HTTPS Only: Always use HTTPS to protect tokens in transit.
- CORS Configuration: Configure CORS properly to prevent unauthorized access from different domains.
- Input Validation: Validate all user inputs to prevent injection attacks.
- Rate Limiting: Implement rate limiting to mitigate brute-force attacks.
- Regular Audits: Regularly review your security practices and code for vulnerabilities.

