Submitted by: M S Sridhar(sridhar.ms@gmail.com)

Wednesday May 6th 2020 by M S Sridhar
Article Image

Language: Java, Expertise: Intermediate - Learn how to use PasswordAuthentication for better data security.

PasswordAuthentication holds the data that will be used by the Authenticator. The username and password are stored in the PasswordAuthentication object. The methods getUserName() and getPassword() are made available and return the userName and password respectively.

import java.net.PasswordAuthentication;

public class UnderstandingPasswordAuthentication
   public static void main(String args[])
      UnderstandingPasswordAuthentication understandingPasswordAuthentication = new UnderstandingPasswordAuthentication();
   private void proceed()
      //Initializing the user name
      String userName = "devUser";
      //Initializing the password - This is a char array since the PasswordAuthentication supports this argument
      char[] password = {'d','e','v','U','s','e','r'};
      PasswordAuthentication passwordAuthentication = new PasswordAuthentication(userName, password);
      System.out.println("Details being retrieved from PasswordAuthentication object post initializing");
      System.out.println("UserName: " + passwordAuthentication.getUserName());
      //The below getPassword actually returns the reference to the password as per the Java API documentation.
      System.out.println("Password: " + passwordAuthentication.getPassword());
      //You can get the password in normal string 
      System.out.println("Password: " + String.copyValueOf(passwordAuthentication.getPassword()));


Expected output:

[root@mypc]# java UnderstandingPasswordAuthentication
Details being retrieved from PasswordAuthentication object post initializing
UserName: devUser
Password: [C@15db9742
Password: devUser

Mobile Site | Full Site