Apache HttpClient Basic Authentication Examples

This tutorial will illustrate how to configure Basic Authentication on the Apache HttpClient 4.5+.
Related Apache HttpClient useful articles:
If you want to dig deeper and learn other cool things you can do with the HttpClient – head on over to the main Apache HttpClient tutorial.

Basic User Authentication using HttpClient

This is a simple example uses HttpClient to execute an HTTP request against a target site that requires user authentication. In this example, we are using http://httpbin.org site which exposed few sample Rest services.
HttpClient provides a CredentialsProvider class to configure Basic Authentication in a standard way:
package com.javadevelopersguide.httpclient.siteexamples;

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * A simple example that uses HttpClient to execute an HTTP request against
 * a target site that requires user authentication.
 * @author Ramesh Fadatare
 */
public class ClientAuthentication {

    public static void main(String[] args) throws Exception {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            new AuthScope("httpbin.org", 80),
            new UsernamePasswordCredentials("user", "passwd"));
        CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .build();
        try {
            HttpGet httpget = new HttpGet("http://httpbin.org/basic-auth/user/passwd");

            System.out.println("Executing request " + httpget.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

Output

Executing request GET http://httpbin.org/basic-auth/user/passwd HTTP/1.1
----------------------------------------
HTTP/1.1 200 OK
{
  "authenticated": true, 
  "user": "user"
}

Preemptive Basic Authentication

Out of the box, the HttpClient doesn’t do preemptive authentication – this has to be an explicit decision made by the client.
First, we need to create the HttpContext – pre-populating it with an authentication cache with the right type of authentication scheme pre-selected.

Preemptive Basic Authentication Example

An example of HttpClient can be customized to authenticate preemptively using BASIC scheme. Generally, preemptive authentication can be considered less secure than a response to an authentication challenge and therefore discouraged.
package com.javadevelopersguide.httpclient.siteexamples;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * An example of HttpClient can be customized to authenticate
 * preemptively using BASIC scheme.
 * <b>
 * Generally, preemptive authentication can be considered less
 * secure than a response to an authentication challenge
 * and therefore discouraged.
 * @author Ramesh Fadatare
 */
public class ClientPreemptiveBasicAuthentication {

    public static void main(String[] args) throws Exception {
        HttpHost target = new HttpHost("httpbin.org", 80, "http");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("user", "passwd"));
        CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider).build();
        try {

            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            // Generate BASIC scheme object and add it to the local
            // auth cache
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(target, basicAuth);

            // Add AuthCache to the execution context
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            HttpGet httpget = new HttpGet("http://httpbin.org/hidden-basic-auth/user/passwd");

            System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
            CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

Output

Executing request GET http://httpbin.org/hidden-basic-auth/user/passwd HTTP/1.1 to target http://httpbin.org:80
----------------------------------------
HTTP/1.1 200 OK
{
  "authenticated": true, 
  "user": "user"
}

References

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments