I was performing evaluation on various SaaS API based Email service provider and had come across some of them which requires HTTP Basic Authentication when accessing their APIs. So, I though its a good reason for me to document this anyone who requires needs to perform Basic Authentication through a generic JAX-RS REST Client or any other HTTP Client. Some HTTP Client already has BasicAuthentication filters while others don’t. So, it is good to just begin with a simple understanding of the authentication mechanism works and you can then reuse this information provided here for any other implementation.

The Basics of HTTP Basic Access Authentication

In simple words, Basic Authentication mechanism is an authentication mechanism on the server side which requires just the username and password, but in a very specific HTTP header format to be sent along with the HTTP request, which is shown just right below.

HTTP Header Format for Basic Authentication

Authorization: Basic <username:password in base64 encoding>

“Authorization” is the header name, and the value should be something like “Basic YXBpOmtleS03Y2IzODY4ZWI5MmM2ZzFlZmY3NzY1YWExZDhmNmE0OQ==“, yes, the word “Basic” must precede the Base64 encoded username:password with the ‘:‘ as separator.

Building the Authorization Header Name and Value (Pre-Java 8)

To build the header value with Base64 encoding tools, here’s how you can do it with Java SE 7 (with the help of javax.xml.bind.DatatypeConverter):

Making Basic Authentication Request Through JAX-RS REST Client

With all the above, Basic Authentication HTTP request could be make through a generic JAX-RS REST client just by appending a HTTP header info into the request. Here’s a complete unit test example of to make things happen.