Django in Azure - CSRF Errors for existing URL in CSRF_TRUSTED_ORIGINS list

Deployed as web app in Azure and added my custom purchased domain name, lets call it 'i-heart-java.com'. I added the URL into the ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS lists, both as https and http, including with extra 'www.' entries. App pulls up successfully on those URL's and my page works for the most part, except when logging into any part of the app ONLY WITH MY CUSTOM DOMAIN, otherwise login works fine with the azure default domain. Error shows

2024-09-24T14:24:35.1649753Z Forbidden (Origin checking failed - https://www.i-heart-java.com does not match any trusted origins.): /admin/login/

My settings are as follows, sanitized the real names for obvious reasons:

ALLOWED_HOSTS = [
    'https://127.0.0.1:8000',
    '127.0.0.1',
    'https://i-heart-java-XXX.eastus-0X.azurewebsites.net/',
    "http://i-heart-java.com",
    'https://i-heart-java.com/',
    "http://www.i-heart-java.com",
    'https://www.i-heart-java.com/',
    ..others..,
]

SESSION_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = False
CORS_ALLOW_ALL_ORIGINS = True

CSRF_COOKIE_SECURE  = True
CSRF_COOKIE_HTTPONLY    = True
CSRF_USE_SESSIONS   = False
CSRF_COOKIE_SAMESITE    = 'Lax'

CSRF_TRUSTED_ORIGINS=[
    "https://i-heart-java.com",
    "http://i-heart-java.com",
    "https://www.i-heart-java.com",
    "http://www.i-heart-java.com",
    ..others..,
]

What could be causing the CSRF trigger only when logging in via my custom domain even though I have all my hostnames and URLs in the right places?

Could it be the custom domain DNS? (please tell me no)

I reconfirmed the custom domain DNS settings in the Azure web app and also my domain host. I also added every kind of URL format of my custom domain I could think of. And also attempted to adjust related CSRF and SSL settings

You do not need http:// entries unless you are specifically serving the site over both http and https. If you are enforcing HTTPS with SESSION_COOKIE_SECURE = True and CSRF_COOKIE_SECURE = True, focus only on https versions.

Update ALLOWED_HOSTS:

ALLOWED_HOSTS = [
    '127.0.0.1',
    'i-heart-java-XXX.eastus-0X.azurewebsites.net',
    'i-heart-java.com',
    'www.i-heart-java.com',
]
  • Django's recent changes require the use of the full scheme (e.g., https://) in CSRF_TRUSTED_ORIGINS. Additionally, you must include a wildcard for subdomains if needed.
CSRF_TRUSTED_ORIGINS = [
    "https://*.i-heart-java.com",  # Wildcard for any subdomains
]

Reference:

Back to Top