Basic Authentication with Java

Note: For a broader discussion about authentication and authorization related to Infinity Web APIs, see Authentication and Authorization.

ZIP file containing Java code for this example:

Note: The bindings were removed from the zipped project.

Topic containing commented Java code for this example:

Note: The example uses a JAXB binding and other classes. The topic code sample does not show these. Please refer to the zipped project for those details.

You can add an Authenticator to your Java client:

    static class BasicAuthenticator extends Authenticator {
        String baName;
        String baPassword;
        private BasicAuthenticator(String baName1, String baPassword1) {
            baName = baName1;
            baPassword = baPassword1;
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(baName, baPassword.toCharArray());

The Authenticator requires these imports:


Class description: Authenticator

Then you can set the default Authenticator to an instance of your Authenticator:

        String name = "domain\\name";
        String password = "password";
        Authenticator.setDefault(new BasicAuthenticator(name, password));

A dialog or some other method is of course preferable to hard-coded Strings for the name and password. But this is just an example to show how it can be done. Username and passwords should be secured and configurable.

When you send an HTTP message, the Authenticator negotiates the credentials.

Further information from Oracle, see HTTP Authentication.