Blog | G5 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:

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:

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.

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.

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

Exit mobile version