Authentication routines

What is Authentication?

Authentication is the process of verifying that a user is who they claim to be before granting them access to a program or system. The most common form uses two pieces of information: a username (which identifies who the user is) and a password (which proves it). The program compares what the user enters against stored credentials - if both match, access is granted; if either is wrong, access is denied.

At GCSE level, credentials are stored as plain-text constants or variables directly in the program. In real systems, passwords would never be stored in plain text - they would be hashed - but understanding the logic of the authentication routine is the key skill here.

TermMeaning
UsernameIdentifies the user - does not need to be secret.
PasswordProves the user's identity - must be kept secret.
CredentialsThe username and password together.
AuthenticationThe check that compares entered credentials against stored ones.

Authentication Routines

The tabs below show three versions of an authentication routine, each adding a layer of realism. The credentials used throughout are username admin and password pa55word, stored as constants.

Single Attempt - Basic Login Check

The simplest authentication routine asks the user to enter a username and password once, compares both against stored constants, and either grants or denies access. The username and password are compared using equality - both must match exactly (including upper/lower case).

# Python -- basic single-attempt authentication

CORRECT_USERNAME = "admin"             # stored credentials (plain text)
CORRECT_PASSWORD = "pa55word"

def authenticate():
    username = input("Username: ")
    password = input("Password: ")
    if username == CORRECT_USERNAME and password == CORRECT_PASSWORD:
        return True                    # both match: access granted
    else:
        return False                   # either wrong: access denied

if authenticate():
    print("Access granted. Welcome!")
else:
    print("Access denied. Incorrect username or password.")
' VB.NET -- basic single-attempt authentication

Const CORRECT_USERNAME As String = "admin"    ' stored credentials (plain text)
Const CORRECT_PASSWORD As String = "pa55word"

Function authenticate() As Boolean
    Dim username As String
    Dim password As String
    Console.Write("Username: ")
    username = Console.ReadLine()
    Console.Write("Password: ")
    password = Console.ReadLine()
    If username = CORRECT_USERNAME And password = CORRECT_PASSWORD Then
        Return True                           ' both match: access granted
    Else
        Return False                          ' either wrong: access denied
    End If
End Function

If authenticate() Then
    Console.WriteLine("Access granted. Welcome!")
Else
    Console.WriteLine("Access denied. Incorrect username or password.")
End If
// C# -- basic single-attempt authentication

const string CORRECT_USERNAME = "admin";      // stored credentials (plain text)
const string CORRECT_PASSWORD = "pa55word";

static bool Authenticate()
{
    Console.Write("Username: ");
    string username = Console.ReadLine();
    Console.Write("Password: ");
    string password = Console.ReadLine();
    if (username == CORRECT_USERNAME && password == CORRECT_PASSWORD)
        return true;                          // both match: access granted
    else
        return false;                         // either wrong: access denied
}

if (Authenticate())
    Console.WriteLine("Access granted. Welcome!");
else
    Console.WriteLine("Access denied. Incorrect username or password.");

Limited Attempts - Lockout After 3 Tries

A more realistic routine gives the user a fixed number of attempts (typically 3) before locking them out. A counter tracks how many attempts have been used. If the credentials are correct, the loop exits early and access is granted. If all attempts are used up without a correct entry, access is permanently denied for that session.

# Python -- authentication with 3-attempt lockout

CORRECT_USERNAME = "admin"
CORRECT_PASSWORD = "pa55word"
MAX_ATTEMPTS = 3

def authenticate():
    attempts = 0                           # counter starts at zero
    while attempts < MAX_ATTEMPTS:
        username = input("Username: ")
        password = input("Password: ")
        if username == CORRECT_USERNAME and password == CORRECT_PASSWORD:
            return True                    # correct: exit loop, grant access
        else:
            attempts = attempts + 1
            remaining = MAX_ATTEMPTS - attempts
            if remaining > 0:
                print("Incorrect. " + str(remaining) + " attempt(s) remaining.")
    return False                           # all attempts used: deny access

if authenticate():
    print("Access granted. Welcome!")
else:
    print("Account locked. Too many failed attempts.")
' VB.NET -- authentication with 3-attempt lockout

Const CORRECT_USERNAME As String = "admin"
Const CORRECT_PASSWORD As String = "pa55word"
Const MAX_ATTEMPTS As Integer = 3

Function authenticate() As Boolean
    Dim attempts As Integer = 0            ' counter starts at zero
    Dim username As String
    Dim password As String
    Do While attempts < MAX_ATTEMPTS
        Console.Write("Username: ")
        username = Console.ReadLine()
        Console.Write("Password: ")
        password = Console.ReadLine()
        If username = CORRECT_USERNAME And password = CORRECT_PASSWORD Then
            Return True                    ' correct: exit loop, grant access
        Else
            attempts = attempts + 1
            Dim remaining As Integer = MAX_ATTEMPTS - attempts
            If remaining > 0 Then
                Console.WriteLine("Incorrect. " & remaining & " attempt(s) remaining.")
            End If
        End If
    Loop
    Return False                           ' all attempts used: deny access
End Function

If authenticate() Then
    Console.WriteLine("Access granted. Welcome!")
Else
    Console.WriteLine("Account locked. Too many failed attempts.")
End If
// C# -- authentication with 3-attempt lockout

const string CORRECT_USERNAME = "admin";
const string CORRECT_PASSWORD = "pa55word";
const int MAX_ATTEMPTS = 3;

static bool Authenticate()
{
    int attempts = 0;                      // counter starts at zero
    while (attempts < MAX_ATTEMPTS)
    {
        Console.Write("Username: ");
        string username = Console.ReadLine();
        Console.Write("Password: ");
        string password = Console.ReadLine();
        if (username == CORRECT_USERNAME && password == CORRECT_PASSWORD)
            return true;                   // correct: exit loop, grant access
        else
        {
            attempts++;
            int remaining = MAX_ATTEMPTS - attempts;
            if (remaining > 0)
                Console.WriteLine("Incorrect. " + remaining + " attempt(s) remaining.");
        }
    }
    return false;                          // all attempts used: deny access
}

if (Authenticate())
    Console.WriteLine("Access granted. Welcome!");
else
    Console.WriteLine("Account locked. Too many failed attempts.");

Extension - Credentials Loaded from a Text File

Instead of hard-coding credentials, a more flexible approach reads them from a text file at runtime. The file contains exactly two lines: the username on line 1 and the password on line 2. This means credentials can be changed by editing the file without touching the program code.

The file used in these examples is called credentials.txt and must be saved in the same folder as the program. Its contents are:

admin
pa55word
# Python -- authentication with credentials read from file
# credentials.txt must contain: line 1 = username, line 2 = password

def loadCredentials(filename):
    with open(filename, "r") as f:
        storedUsername = f.readline().strip()   # read line 1, remove newline
        storedPassword = f.readline().strip()   # read line 2, remove newline
    return storedUsername, storedPassword

def authenticate(filename):
    storedUsername, storedPassword = loadCredentials(filename)
    username = input("Username: ")
    password = input("Password: ")
    if username == storedUsername and password == storedPassword:
        return True
    else:
        return False

if authenticate("credentials.txt"):
    print("Access granted. Welcome!")
else:
    print("Access denied. Incorrect username or password.")
' VB.NET -- authentication with credentials read from file
' credentials.txt must contain: line 1 = username, line 2 = password

Imports System.IO

Function loadCredentials(ByVal filename As String) As String()
    Dim lines() As String = File.ReadAllLines(filename)
    Return lines                           ' returns array: index 0 = username, 1 = password
End Function

Function authenticate(ByVal filename As String) As Boolean
    Dim creds() As String = loadCredentials(filename)
    Dim storedUsername As String = creds(0)
    Dim storedPassword As String = creds(1)
    Console.Write("Username: ")
    Dim username As String = Console.ReadLine()
    Console.Write("Password: ")
    Dim password As String = Console.ReadLine()
    If username = storedUsername And password = storedPassword Then
        Return True
    Else
        Return False
    End If
End Function

If authenticate("credentials.txt") Then
    Console.WriteLine("Access granted. Welcome!")
Else
    Console.WriteLine("Access denied. Incorrect username or password.")
End If
// C# -- authentication with credentials read from file
// credentials.txt must contain: line 1 = username, line 2 = password

using System.IO;

static bool Authenticate(string filename)
{
    string[] lines = File.ReadAllLines(filename);
    string storedUsername = lines[0];      // line 1 = username
    string storedPassword = lines[1];      // line 2 = password

    Console.Write("Username: ");
    string username = Console.ReadLine();
    Console.Write("Password: ");
    string password = Console.ReadLine();

    if (username == storedUsername && password == storedPassword)
        return true;
    else
        return false;
}

if (Authenticate("credentials.txt"))
    Console.WriteLine("Access granted. Welcome!");
else
    Console.WriteLine("Access denied. Incorrect username or password.");

 Key Takeaways

  • Authentication verifies a user's identity by comparing entered credentials against stored ones - both the username and password must match exactly.
  • At GCSE level, credentials are stored as plain-text constants in the program. In real systems, passwords are never stored as plain text - they are hashed for security.
  • A basic routine checks credentials once; a more robust version uses a counter and a loop to allow a limited number of attempts before locking the user out.
  • The authentication routine returns a Boolean value (True/False) so the calling code can decide what to do based on the outcome.
  • In the extension approach, credentials are loaded from a file at runtime, meaning they can be changed without editing the program code.