Java.net.Authenticator class in Java

Authenticator class is used in those cases where an authentication is required to visit some URL. Once it is known that authentication is required, it prompts the user for the same or uses some hard-coded username and password.
To use this class, following steps are followed-

  1. Create a class that extends the Authenticator. Lets name it customAuth.
  2. Override the getPasswordAuthentication() method. This method contains several methods for getting the details of the entity requesting for authentication. All those methods are discussed in detail later.
  3. Set the newly created subclass as the default authenticator to be used when a http server asks for authentcation, with setDefault(Authenticator a) method of Authenticator class.
  4. Methods:

    1. setDefault(Authenticator a) : Sets the authenticator to be used when a HTTP server requires authentication.
      Syntax : public static void setDefault(Authenticator a)
                       throws SecurityException
      Parameter :
      a : authenticator to be set as default
      Throws :
      SecurityException : if security manager doesn't allow 
      setting default authenticator
      
    2. requestPasswordAuthentication() : Asks the authenticator registered with the system for password. Returns username/password or null if not found.
      Syntax : 
      public static PasswordAuthentication requestPasswordAuthentication(
                                                         InetAddress addr,
                                                         int port,
                                                         String protocol,
                                                         String prompt,
                                                         String scheme)
      Parameter :
      addr : Inet address of the site asking for authentication
      port : port of requesting site
      protocol : protocol used for connection
      prompt : message for the user
      scheme : authentication scheme
      Throws :
      SecurityException : if security manager doesn't allow
      setting password authentication.
      

      Another overloaded method which can be used in situations where hostname can be used if inetaddress is not available.



      Syntax : 
      public static PasswordAuthentication requestPasswordAuthentication(
                                                         String host,
                                                         InetAddress addr,
                                                         int port,
                                                         String protocol,
                                                         String prompt,
                                                         String scheme)
      Parameter :
      host : hostname of the site asking for authentication
      addr : Inet address of the site asking for authentication
      port : port of requesting site
      protocol : protocol used for connection
      prompt : message for the user
      scheme : authentication scheme
      Throws :
      SecurityException : if security manager doesn't allow 
      setting password authentication.
      

      Another overloaded method which can be used if URL of the site requesting authentication is only known and not inetaddress and hostname.

      Syntax : 
      public static PasswordAuthentication requestPasswordAuthentication(
                                                         String host,
                                                         InetAddress addr,
                                                         int port,
                                                         String protocol,
                                                         String prompt,
                                                         URL url,
                                                         String scheme)
      Parameter :
      host : hostname of the site asking for authentication
      addr : Inet address of the site asking for authentication
      port : port of requesting site
      protocol : protocol used for connection
      prompt : message for the user
      url : URL of the site requesting authentication
      scheme : authentication scheme
      Throws :
      SecurityException : if security manager doesn't allow 
      setting password authentication.
      
    3. getRequestingHost() : returns the hostname of the site requesting authentication.
      Syntax : protected final String getRequestingHost()
      
    4. getRequestingSite() : returns the inetaddress of the site requesting authentication.
      Syntax : protected final InetAddress getRequestingSite()
      
    5. getRequestingPort() : returns the port of connection.
      Syntax : protected final int getRequestingPort()
      
    6. getRequestingProtocol() : returns the protocol requesting the connection.
      Syntax : protected final String getRequestingProtocol()
      
    7. getRequestingPrompt() : returns the message prompted by requester.
      Syntax : protected final String getRequestingPrompt()
      
    8. getRequestingScheme() : returns the scheme of the of requesting site.
      Syntax : protected final String getRequestingScheme()
      
    9. getPasswordAuthentication() : this method is called when password authentication is required. All subclasses must override this method as default method always returns null.
      Syntax : protected PasswordAuthentication getPasswordAuthentication()
      
    10. getRequestingURL() : returns the url of the requester.
      Syntax : protected final URL getRequestingURL()
      
    11. getRequestorType() : returns if the requestor is proxy or server.
      Syntax : protected Authenticator.RequestorType getRequestorType()
      

    Java Implementation :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Authenticator;
    import java.net.InetAddress;
    import java.net.MalformedURLException;
    import java.net.PasswordAuthentication;
    import java.net.URL;
      
    public class javanetauthenticator 
    {
        public static void main(String[] args) 
        {
      
            try {
      
                // setDefault() method
                // Sets the authenticator that will be used by the networking code
                // when a proxy or an HTTP server asks for authentication.
                Authenticator.setDefault(new CustomAuthenticator());
      
                URL url = new URL("http://securedwebsite.co.in/index.htm");
      
                // read text returned by server
                BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
      
                String line;
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                }
                in.close();
      
            } catch (MalformedURLException e) {
                System.out.println("Malformed URL: " + e.getMessage());
            } catch (IOException e) {
                System.out.println("I/O Error: " + e.getMessage());
            }
      
        }
      
        public static class CustomAuthenticator extends Authenticator 
        {
      
            // getPasswordAuthentication() method
            // Called when password authorization is needed
            protected PasswordAuthentication getPasswordAuthentication() 
            {
      
                // requestPasswordAuthentication() method
                // uncomment this if default authenticator is registered with
                // the system
                // PasswordAuthentication pa=requestPasswordAuthentication
                // (inetaddr, port, protocol, prompt, scheme);
      
                // getRequestingPrompt() method
                String prompt = getRequestingPrompt();
      
                // getRequestingHost() method
                String hostname = getRequestingHost();
      
                // getRequestingSite() method
                InetAddress ipaddr = getRequestingSite();
      
                // getRequestingPort() method
                int port = getRequestingPort();
      
                // getRequestingProtocol() method
                String protocol = getRequestingProtocol();
      
                // getRequestingScheme() method
                String scheme = getRequestingScheme();
      
                // getRequestingURL() method
                URL u = getRequestingURL();
      
                // getRequestorType() method
                RequestorType rtype = getRequestorType();
      
                System.out.println("prompt:" + prompt);
                System.out.println("hostname:" + hostname);
                System.out.println("ipaddress:" + ipaddr);
                System.out.println("port:" + port);
                System.out.println("protocolo:" + protocol);
                System.out.println("scheme:" + scheme);
                System.out.println("URL:" + u);
                System.out.println("Requester Type:" + rtype);
      
                // hardcoded username and password to be used
                // this part can be replaced by an interactive code
                // to take uid and pwd form user
                String username = "admin";
                String password = "admin1";
      
                // Return the information (a data holder that is used by
                // Authenticator)
                return new PasswordAuthentication(username, password.toCharArray());
      
            }
      
        }
    }

    chevron_right

    
    

    Note: This program is just for explaining the flow of Authenticator class programs. The URL used within the program is randomly picked and does not represent any actual URL. This program just shows how the methods of the Authenticator class can be used. Test this program by changing the URL to a server which requires authentication for entering.

    Reference: Official Java Documentation

    This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



    My Personal Notes arrow_drop_up


    Article Tags :
    Practice Tags :


    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.