How to Decode Basic Auth Credentials in Python

Decode username and password from a Basic Auth header string using base64 and standard string operations.

Easy Python 3.9+ Aug 9, 2026 API design & gRPC 13 views 0 copies

Python code

38 lines
Python 3.9+
import 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

stdout
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

  1. Use `base64.b64decode(encoded, validate=True)` to reject non-base64 characters
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from API design & gRPC

Related tutorials and quizzes for this topic.