What is Basic Authentication in REST API: Simple Explanation
username and password encoded in base64 with each request. The server checks these credentials to allow or deny access. It is easy to implement but should be used with HTTPS to keep credentials safe.How It Works
Basic authentication works like showing an ID card to enter a building. When you want to access a protected resource on a server, your client sends your username and password together in a special header called Authorization. These credentials are combined as username:password and then encoded using base64, which is like turning the text into a secret code.
The server receives this encoded string, decodes it back to the username and password, and checks if they match what it expects. If they do, the server lets you in; if not, it denies access. Because the credentials are sent with every request, it’s like showing your ID every time you enter a room.
Since the credentials are only encoded and not encrypted, it’s important to use basic authentication over HTTPS. HTTPS acts like a secure tunnel, keeping your credentials safe from eavesdroppers.
Example
This example shows how to make a request with basic authentication using Python's requests library. It sends the username and password to a server and prints the response status.
import requests url = 'https://httpbin.org/basic-auth/user/passwd' username = 'user' password = 'passwd' response = requests.get(url, auth=(username, password)) print('Status code:', response.status_code) print('Response body:', response.json())
When to Use
Basic authentication is best for simple or internal applications where ease of use is more important than strong security. It is often used in testing, quick prototypes, or when integrating with legacy systems that require simple username and password checks.
Always use it over HTTPS to protect credentials. For public or sensitive applications, stronger methods like OAuth or token-based authentication are recommended.
Key Points
- Basic authentication sends username and password encoded in base64 with each request.
- It requires HTTPS to keep credentials secure during transmission.
- It is simple to implement but not the most secure method.
- Best suited for simple, internal, or testing scenarios.
- Use stronger authentication methods for public or sensitive APIs.