How to construct a HTTP request to an endpoint with HTTP Basic Authentication
The HTTP basic authentication is a mechanism commonly used by web servers to authenticate the sender of a HTTP request. Such a mechanism is usually used to guard server endpoints that are meant to be accessed programmatically.
Almost every new project that I got my hands on required me to create client side coding for accessing server endpoints that use HTTP basic authentication for authenticating the HTTP request sender.
To have a quick reference on how to construct a HTTP request to an endpoint with HTTP basic authentication, I created this post to as a documentation. The steps are agnostic to any programming languages.
Generating the HTTP Basic Authentication string payload from a username and password pair
The first step to constructing the HTTP request to an endpoint with HTTP basic authentication is to generate a string payload from a username and password pair.
Assuming that we have the username and password in the variables
password, we typically go through the following steps to produce the string
- Concatenate username and password with a colon in between:
ucolonp = username + ':' + password
ucolonpto base 64 encoding format and prepend the result with the string 'Basic ':
payload = 'Basic ' + base64encode(ucolonp)
Alternatively, we can collapse the above steps into the following code execution:
payload = 'Basic ' + base64encode(username + ':' + password)
Most programming languages included some library functions to help us with encoding a string in Base64 format. You should replace
base64encode with the respective library function call in the programming language of your choice.
Appending the HTTP Basic Authentication string payload as a HTTP header in the HTTP request
Once you have the Base64 encoded string payload, the last step will be to include it as a HTTP header in the HTTP request that you are going to send to the server. The HTTP header starts with the string "Authorization: " followed by the payload that we had generated earlier.
Typically, the HTTP header is included as a key value pair to a function call, with the string "Authorization" as the key and the base 64 encoded string payload as the value. In such a case, the colon is usually omitted:
You should replace the
httpRequest.addHeader with the respective library function call in the programming language of your choice.