Authentication is the process or action of verifying the identity of a user or process. Apache HttpClient has the capability to test the authentication mechanisms with ease and that is what we are going to see and learn in this tutorial. In this example, we will learn “How to perform Basic Authentication using Apache HttpClient”.
Let’s understand the authentication a bit, In order to login into an email account, you need to provide a username and password in order to prove your authenticity that whether you are a valid user or not.
There are various types of authentication mechanisms are available like Basic Authentication, API Keys, OAuth. In this particular example, we are going to use Basic Authentication mechanism.
Simplest example to understand Basic Authentication mechanism using Apache HttpClient...!!! Click To Tweet
In this tutorial, we are going to cover below topics:
- What is Basic Authentication?
- How to make a GET Request to the resource that requires Username/Password to authenticate?
Check out: BASIC AUTHENTICATION using another popular API testing Framework – REST ASSURED
Let’s begin:
1. What is Basic Authentication?
In this method of authentication, a username and password should be provided by the USER agent to prove their authentication. It’s a straight forward and simple approach which basically uses HTTP header with “username and password” encoded in base64. It does not require cookies, session IDs etc.
2. How to make a GET Request to the resource that requires Username/Password to authenticate?
In order to test this feature, we are going to use a Dummy Rest API available online for testing purpose at http://httpbin.org. This website expose some sample rest services.
A brief description about the web service that we are going to test:
This service provides authenticity if supplied by valid username and password.
1. Request Endpoint : GET
2. Authentication Information :
Valid Username : user
Valid Password : passwd
3. Service Endpoint URL : ‘http://httpbin.org/basic-auth/user/passwd’
4. Expected Response :
1 2 3 | { "authenticated": true, "user": "user" } |
Now, let’s look at the Java code to perform Basic Authentication using HttpClient:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | package org.personal.samples; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; 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.testng.annotations.Test; /** * This class shows how to perform basic authentication using Apache HttpClient library. * @author Deepak Verma */ public class Basic_Authentication_Apache_HttpClient { @Test public void basicAuthenticate() throws ClientProtocolException, IOException { String getEndpoint = "http://httpbin.org/basic-auth/user/passwd"; String validUsername = "user"; String validPassword = "passwd"; CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope("httpbin.org", 80), new UsernamePasswordCredentials(validUsername, validPassword) ); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credentialsProvider) .build(); HttpGet httpGet = new HttpGet(getEndpoint); System.out.println("Executing request " + httpGet.getRequestLine()); HttpResponse response = httpclient.execute(httpGet); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); //Throw runtime exception if status code isn't 200 if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } //Create the StringBuffer object and store the response into it. StringBuffer result = new StringBuffer(); String line = ""; while ((line = br.readLine()) != null) { System.out.println("Response : \n" + result.append(line)); } } } |
Let’s try to understand the code:
1. Specify the URL and Credentials
1 2 3 4 | String getEndpoint = "http://httpbin.org/basic-auth/user/passwd"; String validUsername = "user"; String validPassword = "passwd"; |
2. Create an object of BasicCredentialsProvider class which extends CredentialsProvider interface whose job is to maintain the collection of user credentials
1 2 3 4 5 | CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope("httpbin.org", 80), new UsernamePasswordCredentials(validUsername, validPassword) ); |
3. Set up the CloseableHttpClient object and customize it by supplying the appropriate credentials
1 2 3 | CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credentialsProvider) .build(); |
4. Create a basic Get Request using HttpRequest object and pass the resource URI to it
1 | HttpGet httpget = new HttpGet(getEndpoint); |
5. Submit the Request using HttpGet -> Execute method
1 | HttpResponse response = httpclient.execute(httpget); |
6. Create a BufferedReader object and store the raw Response content into it.
1 | BufferedReader br = new BufferedReader( new InputStreamReader((response.<wbr />getEntity().getContent()))); |
7. Throw runtime exception if status code isn’t 200
1 2 3 | if (response.getStatusLine().<wbr />getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().<wbr />getStatusCode()); } |
8. Create the StringBuffer object and store the response into it.
1 2 3 4 5 6 7 | StringBuffer result = new StringBuffer(); String line = ""; while ((line = br.readLine()) != null) { System.out.println("Response : \n"+result.append(line)); } |
Eclipse Console Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | [RemoteTestNG] detected TestNG version 6.14.3 Executing request GET http://httpbin.org/basic-auth/user/passwd HTTP/1.1 Response : { "authenticated": true, "user": "user"} PASSED: basicAuthenticate =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 =============================================== =============================================== Default suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== |
That’s it, it’s that simple to perform Basic Authentication using Apache HttpClient: ?
Simplest example to understand Basic Authentication mechanism using Apache HttpClient...!!! Click To Tweet
If you like this post, please click like button and share it with others on Twitter. Also, check out my other useful blog posts on Apache HttpClient:
- How to make a GET Request using Apache HttpClient
- How to send a POST Request using Apache HttpClient
- How to send a PUT Request using Apache HttpClient
Other Useful References:
Good post.thanks for sharing this valuable info.