
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
User Authentication in Java
Authentication refers to the process of verifying the identity of an individual to make sure the user is exactly who they are claiming to be before giving access to a system. It is very important to authenticate a user to ensure the security as well as integrity of the system. Over the course of time, authentication has developed into much more advanced and secure methods.
The methods of authentication now range from credentials like user id, password and OTP to finger print scan, face ID scan and much more. Authentication ensures that no sensitive resources are being shared with unauthorised parties and hence protects against malicious attacks as well as complies with the data privacy regulations. On the whole it ensures the CIA (Confidentiality, Integrity and Availability) triad of systems.
There are numerous ways to authenticate users in java and they are as follows ?
Using Strings Only
Using HashMaps
Using a custom user class
Using the Interface
We will now implement each of these methods.
Approach 1: Using Strings Only
This is a very straightforward approach where 2 strings are used to store the actual or valid or correct username and password and 2 strings are used to store the username and password that the person trying to access is entering. After which we simply make use of the .equals() method of java to compare the username and password strings. If both return true i.e. if both the usernames and passwords match, we print to the console "Authentication successful", in the event that it doesn't match it means authentication has failed and hence the corresponding message is displayed.
Example
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."); } } }
Output
Authentication successful!
Approach 2: Using HashMap
HashMaps are a type of key-value data structure wherein the keys and values can be of any data type. The keys must be unique and trying to re-enter a pair with the same key will result in re-writing the original entry. HashMaps are a part of the java.util package. The .put() method can be used to add a key-value pair to the HashMap whereas the .get() method is used to lookup a value with the help of the key and the .containsKey() method is used to check if a particular key exists in a HashMap.
Example
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."); } } }
Output
Authentication successful!
Approach 3: Using a Custom User Class
A class in java is a blueprint which holds the basic properties and methods whereas objects are real world entities.
Example
In this example, we will be defining a class which has 2 properties, the username and password and 2 getter functions to fetch the username and password. The constructor of the classes is used to set the values of username and password. We then create an object of this class and store the username and password field after which we fetch the username and password using the getter functions to compare them with the user entered credentials with help of 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."); } } }
Output
Authentication successful!
Approach 4: Using the Interface
Interfaces are a blueprint of classes and allow us to achieve abstraction. Abstraction means hiding the details of the implementation just like when you drive a car, you need not know the internal workings. Here we create an interface which contains the authenticate method. Interfaces can also be stated as a set of rules that are followed by a class and it provides code reusability.
Example
// 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."); } } }
Output
Authentication successful!
Conclusion
User authentication is extremely important to ensure the CIA (Confidentiality, Integrity and Availability) triad is in place. No unauthorized person shall gain access to any kind of information or data which is why user authentication is added. Over the course of time, authentication methods like OTPs, login id and password, biometrics and much more have been put in place depending upon the use cases. We have implemented user authentication with the help of java which is making use of the login credentials which are username and password.