Home >Java >javaTutorial >Java program demonstrates how to implement user authentication
Authentication is the process of verifying a person's identity to ensure that a user is indeed who they claim to be before granting them access to a system. It is important to authenticate users to ensure the security and integrity of the system. Over time, authentication has evolved into more advanced and secure methods.
Today’s authentication methods range from user ID, password and OTP to fingerprint scanning, face ID scanning and many more. Authentication ensures that sensitive resources are not shared with unauthorized means, protecting against malicious attacks and complying with data privacy regulations. Overall, it ensures the CIA (Confidentiality, Integrity and Availability) triplet of the system.
There are many methods to authenticate users in Java, as shown below −
Use only strings
Use HashMaps
Using custom user classes
Use interface
We will implement these methods now.
This is a very straightforward approach where 2 strings are used to store the actual, valid or correct username and password, and 2 strings are used to store the username and password entered by the person trying to gain access. After that, we just use java's .equals() method to compare the username and password strings. If both return true, that is, the username and password both match, we will print "Authentication Successful" on the console. If they do not match, it means the authentication failed, so the corresponding message is displayed.
public class UserAuthenticationDemo { public static void main(String[] args) { // hardcode the actual username and password String validUsername = "user123"; String validPassword = "password"; // username and password entered by user String username = "user123"; String password = "password"; // Compare the user entered credentials with the actual ones if (username.equals(validUsername) && password.equals(validPassword)) { System.out.println("Authentication successful!"); } else { System.out.println("Authentication failed."); } } }
Authentication successful!
HashMaps is a key-value pair data structure, where the key and value can be any data type. Keys must be unique, attempting to re-enter a key-value pair with the same key will result in the original entry being overwritten. HashMaps are part of the java.util package. Key-value pairs can be added to a HashMap using the .put() method, while values can be found by key using the .get() method, and the .containsKey() method is used to check whether a specific key exists in a HashMap.
import java.util.HashMap; public class UserAuthenticationDemo { public static void main(String[] args) { // Create a HashMap to store valid username and password pairs HashMap<String, String> validUsers = new HashMap<>(); validUsers.put("user123", "password"); validUsers.put("admin", "admin123"); validUsers.put("superuser", "pAsSW0rd#"); //store the username and password entered by user String username="user123"; String password="password"; // Check if the entered username and password match the valid ones in the HashMap if (validUsers.containsKey(username) && validUsers.get(username).equals(password)) { System.out.println("Authentication successful!"); } else { System.out.println("Authentication failed."); } } }
Authentication successful!
In Java, a class is a blueprint that contains basic properties and methods, while an object is an entity in the real world.
In this example, we will define a class that has two properties, username and password, and two getter functions to get the username and password. The constructor of the class is used to set the username and password values. We then create an object of this class and store the username and password fields, after which we use the getter function to get the username and password and then compare them with the credentials entered by the user using the .equals() method.
public class UserAuthenticationDemo { static class User { private String username; private String password; public User(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public String getPassword() { return password; } } public static void main(String[] args) { // Create a User object to store the valid username and password User validUser = new User("user123", "password"); //store the username and password entered by user String username="user123"; String password="password"; // Check if the entered username and password match the valid ones in the User object if (username.equals(validUser.getUsername()) && password.equals(validUser.getPassword())) { System.out.println("Authentication successful!"); } else { System.out.println("Authentication failed."); } } }
Authentication successful!
Interfaces are blueprints for classes that allow us to implement abstractions. Abstraction means hiding the details of the implementation, just like driving a car without knowing the inner workings. Here, we have created an interface containing authenticate method. An interface can also be thought of as a set of rules that are followed by classes and provide code reusability.
// Interface for user authentication interface UserAuthenticator { boolean authenticate(String username, String password); } // Implementation of user authentication interface class SimpleUserAuthenticator implements UserAuthenticator { private String storedUsername = "myusername"; private String storedPassword = "mypassword"; @Override public boolean authenticate(String username, String password) { // Check if the provided credentials match the stored credentials if (username.equals(storedUsername) && password.equals(storedPassword)) { return true; } return false; } } // Main class to demonstrate user authentication public class UserAuthenticationDemo { public static void main(String[] args) { // Create an instance of the SimpleUserAuthenticator class UserAuthenticator authenticator = new SimpleUserAuthenticator(); //store the username and password entered by user String username="myusername"; String password="mypassword"; // Authenticate the user if (authenticator.authenticate(username, password)) { System.out.println("Authentication successful!"); } else { System.out.println("Authentication failed."); } } }
Authentication successful!
User authentication is very important to ensure the existence of the three elements of CIA (confidentiality, integrity and availability). No unauthorized person is allowed to access any type of information or data, which is why user authentication is added. Over time, various authentication methods such as one-time passwords, login IDs and passwords, biometrics, etc. have been adopted depending on usage. We implemented user authentication using Java, using username and password as login credentials.
The above is the detailed content of Java program demonstrates how to implement user authentication. For more information, please follow other related articles on the PHP Chinese website!