Blog | G5 Cyber Security

Secure API Tokens & Sessions

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.

# 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.

3. Token Validation

Every API request must validate the token before granting access.

# 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.

5. Refresh Tokens

To avoid frequent logins, use refresh tokens.

6. Security Considerations

Exit mobile version