Django 4.0 wildcard subdomain preventing from setting csrf token

If you notice the request on the right, the GET as identified at the top is to localhost:8080 and not to admin.localhost:8080. So you’re getting a response from a different “host” than that to which you are sending the request.

I’m not sure if I’m following, let me make sure we are talking about the same thing:
http GET request comes from my frontend http://admin.localhost:8080 and goes to API which is located at http://localhost:8000/api/csrf_cookie
So are you referring to this part?

I’m addressing what’s in the right side of the image you posted.

At the top of the image, it reports an XHR request to http://localhost:8080. The response headers report that the response is coming from admin.localhost. Therefore, you’re getting a response from a different host than the host to which you issued the request.

@KenWhitesell I think that’s exactly what codehooligan is aiming for. They want the cookie to be shared across the subdomains.

@codehooligan An odd thing about the response header is that the Set-Cookie header in the response is that it lacks the domain attribute. That should be controlled by CSRF_COOKIE_DOMAIN. For your example it should be CSRF_COOKIE_DOMAIN = "localhost"

@CodenameTim I can understand the desire to access cookies across domains, I’m unsure of the security issues around the ability to set cookies across domains. That seems problematic to me.

@CodenameTim Just checked prod version with https and I don’t see domain attribute there as well.

@KenWhitesell The cross domain was intentional here, the reason for that is frontend with dynamic/wildcard subdomain.
Frontend: http://wildcardsubdomain.localhost:8080
Backend: http://localhost:8000

Unless I’m going wrong about all this and there is better way to serve wildcard subdomains?

Setting CSRF_COOKIE_DOMAIN = "localhost" as you pointed added domain attribute to the Set-Cookie header, but didn’t help with setting csrf.

@CodenameTim I just added CSRF_COOKIE_DOMAIN = "test.com" to my prod version with https and nginx and it seem like it worked!

I’m gonna do some further testing just to make sure!

Thank you both @KenWhitesell && @CodenameTim for taking a time to help me with my problem!
@CodenameTim your pointer to set CSRF_COOKIE_DOMAIN finally did a trick in my prod environment, since dev is slightly different(no nginx) it’s not working yet but will investigate it later, at least i know it’s doable.

Bellow settings that worked for me:

ALLOWED_HOSTS = ["." + os.environ.get("DOMAIN_NAME")]
CORS_ALLOWED_ORIGIN_REGEXES = [r"https://\w+\.".format(os.environ.get("DOMAIN_NAME"))]
CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_DOMAIN = os.environ.get("DOMAIN_NAME") 
CSRF_TRUSTED_ORIGINS = [
    "https://*." + os.environ.get("DOMAIN_NAME"),
]
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_DOMAIN = os.environ.get("DOMAIN_NAME") 
SESSION_COOKIE_HTTPONLY = True