Authenticator getDefault() in Java

getDefault(): This method is available in the java.net.Authenticator class of Java.

Syntax:

Authenticator java.net.Authenticator.getDefault()

This method gets the default authenticator.

Parameters: NA

Returns: The default authenticator, if set, is null otherwise.

Throws:

1. SecurityException - if a security manager exists and its checkPermission method doesn't allow requesting password authentication.

Approach

Java

package com.Authenticator;

import java.net.Authenticator;
import java.net.PasswordAuthentication;

public class AuthenticatorgetDefault {
    public static void main(String[] args) {

        ClassAuthenticator obj1 = new ClassAuthenticator();
        Authenticator.setDefault(obj1);
        Authenticator authenticator = Authenticator.getDefault();

        System.out.println(authenticator);
    }

    public static class ClassAuthenticator extends Authenticator {
        protected PasswordAuthentication getPasswordAuthentication() {
            this.show();
            String username = "user";
            String password = "password";
            return new PasswordAuthentication(username, password.toCharArray());
        }

        void show() {
            int hostname = getRequestingPort();
            System.out.println("Port Requesting :" + hostname);
        }
    }
}

Output:

com.Authenticator.AuthenticatorgetDefault$ClassAuthenticator@161cd475


Some other methods of Authenticator

getDefault()This method gets the default authenticator.

Authenticator.requestPasswordAuthentication(InetAddress, int, String, String, String)This method asks the authenticator that has been registered with the system for a password.

Authenticator.requestPasswordAuthentication(String, InetAddress, int, String, String, String)This method asks the authenticator that has been registered with the system for a password. This is the preferred method for requesting a password because the hostname can be provided in cases where the InetAddressis not available.

Authenticator.requestPasswordAuthentication(String, InetAddress, int, String, String, String, URL, RequestorType)This method asks the authenticator that has been registered with the system for a password.

Authenticator.requestPasswordAuthentication(Authenticator, String, InetAddress, int, String, String, String, URL, RequestorType)This method asks the given authenticator for a password. If the given authenticator is null, the authenticator, if any, that has been registered with the system using setDefault is used.

Authenticator.requestPasswordAuthenticationInstance(String, InetAddress, int, String, String, String, URL, RequestorType)This method asks this authenticator for a password.

setDefault(Authenticator)This method sets the authenticator that will be used by the networking code when a proxy or an HTTP server asks for authentication.

No comments:

Post a Comment