Basic Authentication is one of the simplest methods for securing API endpoints. It involves sending a username and password encoded in Base64 within the HTTP headers. This method is commonly used when a lightweight authentication mechanism is required. Below are three diverse examples that illustrate how Basic Authentication can be implemented in various scenarios.
In this example, we will demonstrate how a client application can access a user’s profile information from a RESTful API that requires Basic Authentication.
Imagine a scenario where a mobile application needs to retrieve user data from a server. The API endpoint is protected, and the application must authenticate using Basic Authentication.
To authenticate, the mobile application sends an HTTP GET request to the user profile endpoint. The request header includes a Authorization
field with the encoded credentials.
GET /api/v1/user/profile HTTP/1.1
Host: api.example.com
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
In this header, dXNlcm5hbWU6cGFzc3dvcmQ=
is the Base64 encoding of username:password
. Upon receiving this request, the server decodes the credentials and checks them against its user database. If the credentials are valid, the server responds with the user’s profile data. Otherwise, it returns a 401 Unauthorized status.
Notes:
In this example, we will see how a web application can submit data to a protected API endpoint that requires Basic Authentication.
Suppose a web form is used to submit feedback to a server. The feedback endpoint requires users to authenticate before accepting submissions. The following example demonstrates how to submit feedback using Basic Authentication in an HTTP POST request.
POST /api/v1/feedback HTTP/1.1
Host: api.example.com
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Content-Type: application/json
{
"message": "This is my feedback!"
}
In this POST request, the Authorization
header again includes the Base64-encoded credentials. The server processes the feedback and sends back a success response if authentication is successful.
Notes:
This example illustrates how an admin user can manage resources through an API that requires Basic Authentication.
Assume the API allows administrators to manage user accounts. The API endpoint for deleting a user account is secured with Basic Authentication. Here’s how an admin can delete a user account using an HTTP DELETE request:
DELETE /api/v1/users/12345 HTTP/1.1
Host: api.example.com
Authorization: Basic YWRtaW46cGFzc3dvcmQ=
In this request, YWRtaW46cGFzc3dvcmQ=
encodes admin:password
. The server verifies the admin credentials and, if valid, proceeds to delete the specified user account, responding with a success message.
Notes:
These examples of Basic Authentication API Example highlight how this method can be utilized in different contexts, reinforcing the importance of secure practices in API development.