3.2.11 - Authentication routines (C#)

3.2.11 - Authentication routines (C#)

Write a username-and-password check that accepts only a matching pair of credentials. Required written answers use C#. C# execution is unavailable here; the runnable activity is an optional Python demonstration.

Checking identity

Authentication checks a user's claimed identity using evidence such as a username and the password associated with that account.

Authentication

Checking that a user is who they claim to be, for example by checking supplied credentials against the credentials held for that account.

A username identifies the account the person claims to own; the associated password supplies evidence for that claim. A correct username alone is insufficient. Likewise, a password that belongs to a different account does not authenticate this username.

Validation asks whether input meets a rule, such as password length at least eight. Authentication asks whether it matches the account's credentials. abcdefgh could pass the length rule but fail the identity check. Keep these decisions separate when designing a login.

The assessed GCSE routine uses plain-text usernames and passwords; encryption is not required in the written answer. These small classroom examples demonstrate comparison logic. Real services need appropriate secure password handling and further protections; merely storing readable passwords is not a recommended production design.

Writing a username and password check

A simple authentication routine reads both credentials and accepts only when both match the same allowed account.

C#
Console.Write("Username: ");
string username = Console.ReadLine();
Console.Write("Password: ");
string password = Console.ReadLine();
bool authenticated = username == "maya" && password == "pine4";
if (authenticated)
{
    Console.WriteLine("Logged in");
}
else
{
    Console.WriteLine("Invalid login");
}

The AND condition requires both credentials. OR would incorrectly admit someone knowing only the username or only the password. The string comparisons here are exact and case sensitive in native C#; a different case-normalisation policy would need to be explicitly required.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account