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):

Building the Authorization Header Name and Value (Java 8)

To build the header value with Base64 encoding tools, here’s how you can do it with Java SE 8 (with the help of java.util.Base64):

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.

That’s all and hope it help.

References:

Max Lam
About the Author

Born and currently resides in Malaysia, a seasoned Java developer whom had held positions as Senior Developer, Consultant and Technical Architect in various enterprise software development companies.

Related Posts

(adsbygoogle = window.adsbygoogle || []).push({}); There are times that retrieving a large...

Be it X-Form-Urlencoded or JSON HTTP post to a REST resource end-point, there is no specific “data...

By default, JAX-RS Response is cached (at least on Glassfish Application Server). If you are...