3.2.11 - Authentication routines (VB.NET)
Use a username and its matching password to make a simple authentication decision in VB.NET. Native answers are written without Run; the optional Python demonstration checks the same credential-pair rule.
Checking identity
Authentication checks evidence of an asserted identity before a program grants access.
Authentication
Checking that a user is who they claim to be, for example by matching a username with its associated password.
Validation can check that a password is non-empty or long enough. Authentication checks whether it matches the credential stored for this particular username. A long incorrect password can pass validation but fail authentication. Conversely, a classroom account may have a short matching password: its match and its suitability under a separate length policy are different questions.
Both parts of the credential pair must match. If access were allowed when the username matched Or the password matched, someone with a correct username and wrong password could enter. Matching any stored username with any stored password is also insufficient: the password must belong to the same account.
The GCSE task requires only simple plain-text username/password routines; encryption is not required. These visible fixed classroom credentials illustrate logic and are not a production password-storage design. Authentication also differs from authorisation, which determines what an authenticated user may do. A login decision alone does not establish administrator permissions.
Writing a username and password check
A simple routine reads credentials, compares the associated values and returns or displays an appropriate decision.
Dim username As String = Console.ReadLine()
Dim password As String = Console.ReadLine()
If username = "reader1" And password = "Orbit42" Then
Console.WriteLine("Access granted")
Else
Console.WriteLine("Access refused")
End If
For this example, use case-sensitive string comparisons: reader1/Orbit42 succeeds, reader1/wrong fails, and other/Orbit42 fails. VB.NET's comparison behaviour can be configured; an Option Compare Binary setting gives the case-sensitive behaviour assumed here. The task must state any different acceptance rule rather than silently changing case handling.
Several account pairs can be stored at corresponding indexes:
Dim usernames() As String = {"reader1", "reader2"}
Dim passwords() As String = {"Orbit42", "Comet53"}
Dim authenticated As Boolean = False
For index As Integer = 0 To usernames.Length - 1
If usernames(index) = username And passwords(index) = password Then
authenticated = True
End If
Next
If authenticated Then
Console.WriteLine("Access granted")
Else
Console.WriteLine("Access refused")
End If
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account