Get a Pentest and security assessment of your IT network.

Cyber Security

User Authentication Across Services

TL;DR

This guide explains how to securely move an authenticated user between different services (e.g., a web app and an API) without repeatedly asking for their login details. We’ll use tokens – small pieces of data that prove the user is who they say they are.

1. Understanding the Problem

Imagine a user logs into your website. Then, they want to use another part of your system (like an API) or a separate application you own. You don’t want them to have to log in again. That’s frustrating and insecure if done badly.

2. The Solution: Tokens

Tokens act like temporary passes. When a user logs in, your system creates a token for them. This token is then sent with requests to other services. Those services can check the token to verify the user’s identity without needing their username and password.

3. Choosing a Token Type

There are two main types:

  • JSON Web Tokens (JWT): A standard way of creating tokens. They contain information about the user in a secure, encoded format.
  • Session Tokens: Your server stores information about the logged-in user and issues a unique token. This is simpler to implement but requires more server resources.

JWTs are generally preferred for distributed systems as they don’t require shared session storage.

4. Implementing JWT Authentication (Example)

  1. User Login: When a user successfully logs in, create a JWT.
    # Example using Python and the PyJWT library
    import jwt
    import datetime
    
    payload = {
        'user_id': 123,
        'username': 'example_user',
        'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30) # Token expires in 30 minutes
    }
    token = jwt.encode(payload, 'your-secret-key', algorithm='HS256')
    print(token)
    
  2. Sending the Token: Send the token to the client (e.g., in a cookie or as part of an HTTP header).

    Commonly, it’s sent in the Authorization header:

    Authorization: Bearer <your_token>
    
  3. Service Verification: When a request comes to another service, extract the token and verify it.
    # Example using Python and PyJWT library
    token = request.headers.get('Authorization').split()[1] # Extract 'Bearer <token>' 
    try:
    data = jwt.decode(token, 'your-secret-key', algorithms=['HS256'])
        print(data['user_id'])  # Access user information
    except jwt.ExpiredSignatureError:
        # Token has expired
        return "Token Expired", 401
    except jwt.InvalidTokenError:
        # Invalid token
        return "Invalid Token", 401
    

5. Security Considerations

  • Secret Key: Keep your secret key very safe! Don’t hardcode it into your code; use environment variables or a secure configuration management system.
  • Token Expiration: Tokens should expire after a reasonable time to limit the impact of compromised tokens.
  • HTTPS: Always use HTTPS to protect tokens in transit.
  • Refresh Tokens (Optional): Implement refresh tokens to allow users to stay logged in for longer periods without repeatedly entering their credentials. A refresh token is used to get a new access token when the current one expires.

6. Session Token Implementation

  1. Login: When a user logs in, generate a unique session ID and store user data on your server (e.g., in a database or cache).
  2. Token Issuance: Send the session ID as a cookie to the client.
  3. Verification: On each request, check for the session ID cookie. If it exists, retrieve the corresponding user data from your server and validate the session.

Session tokens are simpler but require managing session state on the server.

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