Django doesn't set cookie and doesn't create session

167 views Asked by At

I have a problem setting cookies in Django.

Basically I have 3 different cookie I wanna set:

  1. Session ID
  2. Access token
  3. Refresh token

For some reason Access and Refresh tokens are set, but the Session ID (SSID) doesn't set. If I change key of "SSID" to for example "TEST_COOKIE" it passes and I can see it in dev tools. However I need SSID and for some magical reason it doesn't work.

Here's example of my code:

class AuthResponse(SuccessResponse):
    def __init__(self, data={}, ssid='', access_token: str = '', refresh_token: str = '', **kwargs):
        super().__init__(data, **kwargs)

        self.set_cookie(key=settings.SESSION_COOKIE_NAME,
                        value=ssid,)

        if access_token:
            self.set_cookie(key=settings.ACCESS_KEY_COOKIE_NAME,
                            value=access_token,)
        if refresh_token:
            self.set_cookie(key=settings.REFRESH_KEY_COOKIE_NAME,
                            value=refresh_token,)

AuthResponse inherits from SuccessResponse which is based on DjangoJsonResponse, and DjangoJsonResponse eventually inherits from HttpResponse.

So the question is - what could cause of getting rid of "SSID" cookie?

I tried to look around and find if all the data appears in init function and apprently eveyrthing is fine. All data, ssid, access_token and refresh_token come through, but only "SSID" doesn't get set.

As well I tried to use "httponly" and "secure" while setting cookies, but it didn't help.

There was an idea that might be middleware affects somehow on this, however I don't know who to check this out...

Is there anyone familiar with this who can potentially make an advice of why is this happening?

1

There are 1 answers

0
Vladislav Mikhailov On BEST ANSWER

I found the answer while working on localhost the SESSION_COOKIE_DOMAIN should not be used, so I made it in this way in settings.py:

if website_settings.current_instance != 'dev':
    SESSION_COOKIE_DOMAIN = (
        website_settings.session_cookie_domain
        if website_settings.session_cookie_domain
        else f".{SITE_DOMAIN}"
    )

This way it saves all needed cookies and browser sees them.