Cors Wildcard in Django with Basic Auth
Cors Wildcard in Django with Basic Auth — how this specific combination creates or exposes the vulnerability
Cross-origin resource sharing (CORS) misconfigurations in Django can inadvertently expose Basic Auth credentials when a wildcard origin is used. When ALLOW_CREDENTIALS = True is set alongside Access-Control-Allow-Origin: *, browsers reject the request as insecure because credentials and wildcard origins are mutually compliant only when credentials are not required. However, server-side proxy setups or misapplied middleware can still forward requests to a Django backend that processes Basic Auth headers, creating a scenario where an origin like https://example.com passes credentials, while the response header exposes a wildcard. This mismatch can lead to unauthorized cross-origin access where an attacker’s page running in a browser may leverage cached or intercepted credentials to interact with the API endpoint.
In a black-box scan, middleBrick tests the unauthenticated attack surface and flags CORS issues under the CORS/Wildcard and Authentication checks. When Basic Auth is present, the scanner inspects response headers for permissive values and evaluates whether preflight responses allow credentials. A misconfigured CORSAcceptAllOrigins or manual header injection in Django settings can allow origins that should be denied to participate in authenticated exchanges. The scanner also cross-references these runtime observations with any OpenAPI/Swagger spec definitions that declare securitySchemes of type http with scheme basic, ensuring that declared authentication expectations align with actual runtime behavior.
An attacker who can inject a malicious site may trigger authenticated requests from a victim’s browser if the backend responds with Access-Control-Allow-Credentials: true and Access-Control-Allow-Origin: * or a dynamic origin reflecting the request’s Origin header without strict validation. Because Basic Auth sends credentials in an Authorization header on every request, these responses can facilitate credential leakage across origins. The CORS misconfiguration does not directly leak the password hash, but it can expose the Base64-encoded credentials to a malicious page that reads the response, especially when combined with other weaknesses like missing CSRF protections on state-changing endpoints.
middleBrick’s 12 security checks run in parallel and include Property Authorization and Input Validation to catch cases where permissive CORS rules intersect with endpoint-level authorization gaps. The scanner’s Authentication check verifies whether endpoints that expect Basic Auth are truly unauthenticated during the scan, and reports findings when credentials are accepted without proper enforcement. By mapping results to frameworks like OWASP API Top 10 and SOC2, the tool helps teams understand the compliance implications of a wildcard origin in combination with Basic Auth in Django deployments.
Basic Auth-Specific Remediation in Django — concrete code fixes
Remediation centers on tightening CORS settings and ensuring that Basic Auth is only accepted over HTTPS with strict origin policies. Below are concrete, syntactically correct Django configurations and view examples that address the intersection of CORS and Basic Auth.
1. Secure CORS settings
Instead of allowing all origins, explicitly list trusted origins and disable credentials for wildcard scenarios. If credentials are required, list origins individually.
# settings.py
INSTALLED_APPS = [
...,
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
...,
]
# Allow only specific origins and credentials
CORS_ALLOWED_ORIGINS = [
'https://app.yourdomain.com',
'https://admin.yourdomain.com',
]
CORS_ALLOW_CREDENTIALS = True # Only set to True if you explicitly list origins above
# Ensure no wildcard is used when credentials are true
CORS_ORIGIN_ALLOW_ALL = False
2. Enforce HTTPS and Basic Auth at the view level
Use Django’s built-in authentication classes and require secure transport. The following example demonstrates a view that validates HTTP Basic Authentication and rejects requests on non-HTTPS in production.
# views.py
from django.contrib.auth import authenticate
from django.http import JsonResponse, HttpResponse
from django.views import View
from django.utils.decorators import method_decorator
from django.views.decorators.http import require_http_methods
import base64
class SecureBasicAuthView(View):
@method_decorator(require_http_methods(["GET", "POST"])
def dispatch(self, request, *args, **kwargs):
# Enforce HTTPS in production
if not request.is_secure():
return JsonResponse({'error': 'HTTPS required'}, status=403)
auth = request.META.get('HTTP_AUTHORIZATION', '')
if not auth.lower().startswith('basic '):
return HttpResponse(status=401, headers={'WWW-Authenticate': 'Basic realm="api"'})
try:
decoded = base64.b64decode(auth.split(' ', 1)[1]).decode('utf-8')
username, password = decoded.split(':', 1)
user = authenticate(request, username=username, password=password)
if user is not None:
# Proceed with business logic
return JsonResponse({'status': 'ok'})
return HttpResponse(status=401, headers={'WWW-Authenticate': 'Basic realm="api"'})
except Exception:
return HttpResponse(status=400)
3. Use middleware to reject wildcard origins dynamically
For additional assurance, add a lightweight middleware that validates the Origin header when credentials are present.
# middleware.py
from django.http import HttpResponseForbidden
TRUSTED_ORIGINS = {
'https://app.yourdomain.com',
'https://admin.yourdomain.com',
}
class StrictCorsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
origin = request.META.get('HTTP_ORIGIN')
if origin and request.META.get('HTTP_AUTHORIZATION'):
if origin not in TRUSTED_ORIGINS:
response['Access-Control-Allow-Origin'] = ''
response.status_code = 403
return response
4. Combine with CSRF protection for state-changing methods
When using Basic Auth, ensure that mutating endpoints also validate CSRF tokens for same-origin browser requests, or explicitly exempt API views if they are intended to be consumed by external clients using token-based schemes.
middleBrick’s GitHub Action can be added to CI/CD pipelines to automatically detect CORS misconfigurations and weak authentication setups before deployment. Its CLI allows you to scan specific endpoints with middlebrick scan <url> and review JSON output that highlights CORS and authentication issues with severity and remediation guidance.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |