Get a Pentest and security assessment of your IT network.

Cyber Security

Secure Authentication Tokens

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

  1. 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.
  2. 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.
  3. 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)
      
  4. 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 HttpOnly and Secure flags on cookies for security. HttpOnly prevents JavaScript access, mitigating XSS attacks. Secure ensures 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.
  5. Send the Token with Subsequent Requests: The client must include the token in every subsequent request to protected resources.
    • Authorization Header: Use the Authorization header with a Bearer scheme:
      Authorization: Bearer <token>
      
  6. Verify the Token on Each Request: On your server, for each protected resource:
    • Extract the token from the Authorization header.
    • 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).
  7. 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.
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation