Blog | G5 Cyber Security

Secure Automatic Login URLs

TL;DR

Automatic login URLs are convenient but risky. This guide shows you how to create them securely using tokens and strong validation, minimising the chance of unauthorised access.

1. Understand the Risks

Directly embedding usernames or passwords in a URL is extremely insecure. Anyone with access to browser history, logs, or even a shared link could compromise your system. We’ll focus on using short-lived tokens instead.

2. Generate Unique Tokens

  1. Choose a strong token generation method: Use a cryptographically secure random number generator (CSRNG). Many programming languages have built-in functions for this.
  2. Token Length: Tokens should be long enough to make guessing impractical – at least 32 characters is recommended.
  3. Example (Python):
    import secrets
    import string
    
    def generate_token(length=32):
        alphabet = string.ascii_letters + string.digits
        return ''.join(secrets.choice(alphabet) for i in range(length))
    token = generate_token()
    print(token)
  4. Store Tokens Securely: Tokens must be stored securely on the server, associated with a user account. Use a database and encrypt sensitive data at rest.

3. Create the Login URL

  1. URL Structure: Include the token as a parameter in your login URL. For example:
    https://yourwebsite.com/login?token=[TOKEN]
  2. Token Expiration: Set an expiration time for each token (e.g., 15 minutes). This limits the window of opportunity for misuse.

4. Validate the Token on Login

  1. Retrieve the Token: Extract the token from the URL parameters.
  2. Check Database: Verify that the token exists in your database and is associated with a valid user account.
  3. Expiration Check: Ensure the token has not expired.
  4. One-Time Use: Mark the token as used immediately after successful login to prevent it from being reused. This is crucial!
  5. Example (Conceptual):
    # Pseudo-code - adapt to your language/framework
    token = request.query_params['token']
    db_record = database.get_token(token)
    if db_record and db_record.is_valid and db_record.expires > now():
        user = db_record.user
        db_record.used = True
        database.save(db_record)
        login_user(user)
    else:
        display_error("Invalid or expired token")

5. Additional Security Measures

6. Alternatives

If possible, consider using more secure authentication methods like:

Exit mobile version