Overview
The RestAPI project usesdjango-cors-headers to handle Cross-Origin Resource Sharing (CORS). This allows your API to accept requests from frontend applications hosted on different domains.
Installation
Thedjango-cors-headers package is included in the project. Verify it’s in your INSTALLED_APPS:
RestAPI/settings.py
MIDDLEWARE:
RestAPI/settings.py
The
CorsMiddleware must be placed before CommonMiddleware in the middleware list.Configuration Modes
CORS behavior changes based on theDEBUG environment variable:
Development Mode (DEBUG=True)
In development, CORS is configured permissively to allow easy testing:RestAPI/settings.py
Allows requests from any origin in development mode.
Accepts requests to any host in development.
Allows all HTTP headers in development.
Production Mode (DEBUG=False)
In production, CORS is restricted to specific trusted origins:RestAPI/settings.py
Allows cookies and authentication credentials to be included in cross-origin requests.
Disables unrestricted CORS access in production.
Whitelist of allowed origins in production. Only these domains can make requests to your API.Example:
List of host/domain names that Django will serve. This is a security measure to prevent HTTP Host header attacks.
Allowed HTTP Methods
The API accepts the following HTTP methods:RestAPI/settings.py
Allowed Headers
In production mode, specific headers are whitelisted:RestAPI/settings.py
The
authorization header is included to support JWT authentication with rest_framework_simplejwt.Adding Custom Origins
To add new allowed origins in production, updateCORS_ALLOWED_ORIGINS in settings.py:
Testing CORS Configuration
Development Testing
WithDEBUG=True, test from any origin:
Production Testing
Verify CORS headers are present:Common CORS Issues
Origin Not Allowed
Error:Access to fetch at '...' from origin '...' has been blocked by CORS policy
Solution: Add the origin to CORS_ALLOWED_ORIGINS:
Credentials Not Allowed
Error:The value of the 'Access-Control-Allow-Credentials' header is '' when credentials are needed
Solution: Ensure CORS_ALLOW_CREDENTIALS = True in production mode.
Method Not Allowed
Error:Method PUT is not allowed by Access-Control-Allow-Methods
Solution: Verify the method is in CORS_ALLOW_METHODS.
Header Not Allowed
Error:Request header 'Authorization' is not allowed by Access-Control-Allow-Headers
Solution: Add the header to CORS_ALLOW_HEADERS (it’s already included by default).
Security Best Practices
Production Checklist:
- Set
DEBUG=False - Use specific origins in
CORS_ALLOWED_ORIGINS(never use*) - Enable
CORS_ALLOW_CREDENTIALSonly if needed - Use HTTPS for all production origins
- Regularly audit allowed origins
- Remove unused origins from the whitelist
Avoid Wildcards in Production
Never use wildcard origins in production:Credentials and Authentication
When using JWT authentication:Frontend Request
Advanced Configuration
For more complex CORS requirements, you can add additional settings:RestAPI/settings.py