How to Decode Basic Auth Credentials in Python
Decode username and password from a Basic Auth header string using base64 and standard string operations.
Python code
38 linesimport base64
def decode_basic_auth(header_value):
"""
Decode credentials from a Basic Auth header value.
Expected format: "Basic base64encoded(username:password)"
Returns a tuple (username, password).
"""
if not header_value.startswith("Basic "):
raise ValueError("Invalid Basic Auth header format")
encoded_part = header_value.split(" ", 1)[1]
decoded_bytes = base64.b64decode(encoded_part)
decoded_str = decoded_bytes.decode("utf-8")
if ":" not in decoded_str:
raise ValueError("Decoded credentials missing ':' separator")
username, password = decoded_str.split(":", 1)
return username, password
if __name__ == "__main__":
# Mock test credentials
test_username = "admin"
test_password = "secret123"
# Encode for the mock header
raw_credentials = f"{test_username}:{test_password}"
encoded_credentials = base64.b64encode(raw_credentials.encode("utf-8")).decode("utf-8")
mock_header = f"Basic {encoded_credentials}"
print(f"Mock header: {mock_header}")
# Decode and display
username, password = decode_basic_auth(mock_header)
print(f"Decoded username: {username}")
print(f"Decoded password: {password}")
Output
Mock header: Basic YWRtaW46c2VjcmV0MTIz
Decoded username: admin
Decoded password: secret123
How it works
The code checks that the header starts with 'Basic ' and extracts the encoded portion. It then uses base64.b64decode to convert the base64 string back to bytes and decodes it as UTF-8 text. The decoded string is split on the first colon to separate the username and password. Proper error handling raises clear errors if the header format or decoded value is invalid.
Common mistakes
- Forgetting to decode the base64 bytes to a string before splitting
- Not validating that the header starts with 'Basic '
- Assuming the username or password contains no colon
Variations
- Use `base64.b64decode(encoded, validate=True)` to reject non-base64 characters
- Read credentials from an HTTP request header via a web framework like Flask or FastAPI
Real-world use cases
- Implementing authentication middleware for an internal REST API that accepts Basic Auth
- Testing API endpoints with mocked headers in integration tests or during local development
- Parsing credentials from webhook callbacks where the provider sends Basic Auth in the request
Sponsored
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
Keep learning
Related tutorials and quizzes for this topic.