Blog | G5 Cyber Security

Secure Client-Side Auth Tokens

TL;DR

Storing auth tokens securely in a browser is tricky. Use HTTP-only cookies whenever possible. If you must use local storage or session storage, encrypt the token and be aware of XSS risks. Regularly rotate tokens and implement robust security measures.

1. Why Client-Side Storage Is Risky

Client-side storage (local storage, session storage) is vulnerable to Cross-Site Scripting (XSS) attacks. If an attacker injects malicious JavaScript into your website, they can access tokens stored in these locations.

2. Best Option: HTTP-Only Cookies

HTTP-only cookies are the most secure way to store auth tokens client-side. They are inaccessible to JavaScript, mitigating XSS risks. The server sets these cookies and the browser automatically includes them in requests.

from flask import Flask, make_response

app = Flask(__name__)

@app.route('/login')
def login():
    token = 'your_auth_token'
    resp = make_response('Login successful!')
    resp.set_cookie('auth_token', token, httponly=True, samesite='Strict') #Important flags!
    return resp
  • Key Considerations:
  • 3. If Cookies Aren’t Possible: Local/Session Storage (Use with Caution)

    If you absolutely must use local or session storage, take these steps:

    3.1 Encrypt the Token

    Never store the token in plain text. Use a strong encryption library to encrypt it before storing it.

    const encryptedToken = CryptoJS.AES.encrypt(authToken, 'your_secret_key').toString();
    localStorage.setItem('auth_token', encryptedToken);
    
  • Important: `’your_secret_key’` should be a strong, randomly generated key and managed securely (e.g., environment variables).
  • 3.2 Implement XSS Protection

    Since local/session storage is vulnerable to XSS, you need robust protection:

    3.3 Token Rotation

    Regularly rotate your auth tokens (e.g., every hour, day). This limits the impact of a compromised token.

    4. Additional Security Measures

    Exit mobile version