Skip to content

Instantly share code, notes, and snippets.

@shah-smit
Last active August 23, 2020 05:51
Show Gist options
  • Save shah-smit/e6accd05edb3a4c7861b06d1ea888510 to your computer and use it in GitHub Desktop.
Save shah-smit/e6accd05edb3a4c7861b06d1ea888510 to your computer and use it in GitHub Desktop.
Generate Basic Authorization Header

Authorization Header

In order to consume the API, you will need to pass the Authorization header in the request. The header is generated via the below logic.

The Authorization header consists of username and password which will be provided by the admins or maintainer of this site. However in order not to pass the username and password in the plain text, you will have to encode the value using Base64 library.

Base64 Transformation in different languages

For Java, you may use the below line:

String encoded = new String(Base64.getEncoder().encode((username+":"+password).getBytes()));
String header = "Authorization: Basic "+encoded;

For Angular, you may use the below line:

encoded = btoa(username + ':' + password)
header = "Authorization: Basic "+encoded

Step by Step guide

Here is an example:

Step 1: Retrieve username and password username : testuser password : dummypassword

Step 2: Encode the string in the following format username:password

String encoded = new String(Base64.getEncoder().encode((username+":"+password).getBytes()));

The value of the encoded will be dGVzdHVzZXI6ZHVtbXlwYXNzd29yZA==

Step 3: Now you may use the encoded value in Authorization header

Authorization:Basic dGVzdHVzZXI6ZHVtbXlwYXNzd29yZA==

CURL request will look like:

curl -XGET 
-H 'Authorization: Basic VGVhbUE6dGVhbWFwYXNzd29yZA==' 
-H "Content-type: application/json" 
'http://localhost:5000/customer'

In Angular request will look like:

const headers = new HttpHeaders({
            authorization : 'Basic ' + btoa(username + ':' + password)
        });
Useful Links
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment