Blog | G5 Cyber Security

Desktop App Authentication

TL;DR

This guide shows you how to add secure user logins to your desktop application. We’ll cover storing passwords safely, checking login details, and handling common problems.

1. Choose an Authentication Method

There are several ways to handle authentication. Here are a few options:

For this guide, we’ll focus on a local database using SQLite as it’s common for desktop apps.

2. Install the Necessary Libraries

You’ll need a library to interact with your chosen database. For Python and SQLite, you can use sqlite3 which is usually included by default:

import sqlite3

3. Create the User Database Table

  1. Connect to the database file (create it if it doesn’t exist).
  2. Create a table to store user information. This should include at least username and password hash.

Here’s an example Python snippet:

def create_table():
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE NOT NULL,
            password_hash TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()

4. Securely Store Passwords (Hashing)

Never store passwords in plain text! Use a strong hashing algorithm like bcrypt or Argon2.

In Python, you can use the passlib library:

import passlib.hash

hashed_password = passlib.hash.bcrypt.hash('your_password')
print(hashed_password)

5. Implement User Registration

  1. Get the username and password from the user.
  2. Hash the password using your chosen algorithm.
  3. Insert the username and hashed password into the database.
  4. Handle duplicate usernames gracefully (e.g., show an error message).

6. Implement User Login

  1. Get the username and password from the user.
  2. Retrieve the hashed password for the given username from the database.
  3. Use passlib to verify if the entered password matches the stored hash.
  4. If the passwords match, log the user in; otherwise, show an error message.

Example Python login code:

def authenticate(username, password):
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    cursor.execute('SELECT password_hash FROM users WHERE username = ?', (username,))
    result = cursor.fetchone()
    conn.close()

    if result is None:
        return False  # User not found

    stored_password_hash = result[0]
    return passlib.hash.bcrypt.verify(password, stored_password_hash)

7. Handle Common Errors

8. Consider Two-Factor Authentication

For increased security, implement two-factor authentication (2FA). This requires users to provide a second verification method in addition to their password (e.g., a code from an authenticator app or SMS message).

Exit mobile version