Get a Pentest and security assessment of your IT network.

Cyber Security

Desktop App: Secure User Sessions

TL;DR

This guide shows you how to add secure user sessions to your desktop application. We’ll cover storing session tokens, verifying users on each login, and handling token expiry.

1. Choose a Session Token Method

Session tokens are unique identifiers that prove a user is logged in. Here are some options:

  • UUIDs: Universally Unique Identifiers (UUIDs) are good for simplicity.
  • Random Strings: Generate long, random strings using a secure random number generator.
  • JWTs (JSON Web Tokens): More complex but offer extra features like storing user data directly in the token and easy verification. We’ll focus on UUIDs for this guide as they are easier to implement.

2. Generate a Session Token on Login

When a user successfully logs in, create a new session token:

import uuid

token = str(uuid.uuid4())

Store this token securely (see step 3).

3. Securely Store Session Tokens

Important: Never store tokens in plain text! Here are some options:

  • Database: The most secure option. Use a database designed for security, and hash the token before storing it (e.g., using bcrypt).
  • Encrypted File: If a database isn’t feasible, encrypt the file containing tokens with a strong key.
  • In-Memory Storage (with caution): Suitable only for short-lived sessions and non-critical applications. The token is lost when the application restarts.

Example using a database (pseudocode):

# Assuming you have a 'users' table with a 'token' column
db.execute("UPDATE users SET token = ? WHERE username = ?", (hashed_token, username))

4. Send the Token to the Client

After generating and storing the token, send it back to the desktop application.

  • HTTP Response Header: If your app communicates via HTTP(S), use a secure header like Authorization: Bearer <token>.
  • Custom Data Format: For other communication methods, include the token in a secure data format (e.g., JSON).

5. Verify the Token on Each Request

Every time the user makes a request to a protected resource, verify the session token:

  1. Retrieve the Token: Get the token from the client (e.g., HTTP header or custom data format).
  2. Check if the Token Exists: Look up the token in your secure storage.
  3. Validate the User: If the token exists, verify that it’s associated with a valid user account.

Example (pseudocode):

token = request.headers.get('Authorization').split(' ')[1]
user = db.execute("SELECT * FROM users WHERE token = ?", (token,))
if user:
  # Token is valid
  # Proceed with the request
else:
  # Token is invalid
  # Return an error

6. Handle Token Expiry

Tokens should expire to limit the impact of compromised tokens.

  • Time-Based Expiry: Add a expires_at timestamp when storing the token.
  • Automatic Logout: Regularly check for expired tokens and force logout if necessary.
  • Refresh Tokens (Advanced): Use short-lived access tokens and long-lived refresh tokens to allow users to stay logged in longer without compromising security.

Example (pseudocode – time based expiry):

# When storing the token:
db.execute("UPDATE users SET token = ?, expires_at = ? WHERE username = ?", (hashed_token, datetime.now() + timedelta(hours=1), username))

# On each request:
user = db.execute("SELECT * FROM users WHERE token = ? AND expires_at > ?", (token, datetime.now()))
if user:
  # Token is valid and not expired
else:
  # Token is invalid or expired

7. Security Considerations

  • HTTPS: Always use HTTPS to encrypt communication between the client and server.
  • Token Length: Use sufficiently long tokens (at least 32 characters for UUIDs).
  • Secure Random Number Generator: Ensure your random number generator is cryptographically secure.
  • Regular Security Audits: Regularly review your code and security practices to identify potential vulnerabilities.
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