Django HTTP response always sets `sessionid` cookie and session data do not persist

I have created a custom backend and related middleware which log users in on the sole condition that an ID_TOKEN cookie is passed along with the request (authentication is done by AWS Cognito + Lambda Edge, managed by an AWS CouldFront).

My code is extensively based on django.contrib.auth.backends.RemoteUserBackend and its related middleware middleware django.contrib.auth.middleware.RemoteUserMiddleware.

While dealing with custom session data is working fine both locally and in a Docker container using runserver + unit tests do pass, I lose all session data in production (code running in a container on AWS ECS) from one request/response to another. From what I can see in my Firefox network tab, a set-cookie header is always sent with the HTTP response, causing session data to be lost. I guess they must be flushed as well on the back-end side (sessions use database store, production is running on gunicorn).

I have set SESSION_COOKIE_SECURE = True in production but it did not solve the issue. Moreover, using django_extensions and its runserver_plus with an auto-generated certificate to use HTTPS locally as well did not allow me to reproduce the issue.

Here is one set-cookie example: set-cookie sessionid=rlc...tn; expires=Mon, 03 Feb 2025 14:29:53 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax; Secure

Has anyone dealt with such problem before?

The session is getting flushed due to the following lines in your middleware:

if request.user.is_authenticated:
    if request.user.get_username() == token.username and not has_id_token_digest_changed:
        return  # username and token did not change, do nothing

    self._remove_invalid_user(request)

The call to self._remove_invalid_user(request) is the problem since that is logging the user out, which then flushes the session for security purposes. Since you mention you'd developed this after referencing the RemoteUserMiddleware the corresponding lines there look as follows:

if request.user.is_authenticated:
    if request.user.get_username() == self.clean_username(username, request):
        return self.get_response(request)
    else:
        # An authenticated user is associated with the request, but
        # it does not match the authorized user in the header.
        self._remove_invalid_user(request)

Note that in this case _remove_invalid_user is only called if the username of the remote user didn't match the username of the logged in user. In your case you're calling the method even if the username matched but the ID token did not.

You seem to be trying to check whether the ID token has changed or not by checking its hash, this doesn't seem to make much sense given that the ID token is a JWT which typically doesn't have a long expiry. It is very much possible that the changed token is for the same user identity and is just a replacement of the expired token. If you want to confirm that the token is for the same user you should use some identifying claim from the token for example the sub claim, etc. For now assuming that your username identifies the user uniquely, you can change those lines as follows:

if request.user.is_authenticated:
    if request.user.get_username() == token.username:
        return  # username did not change, do nothing
    else:
        self._remove_invalid_user(request)

Thanks to you Abdul Aziz Barkat, I could narrow the issue down to a too restrictive AWS CloudFront cookie whitelist. Thank you!

Addind both Django's default sessionid and csrftoken cookie names to whitelisted cookies solved my issue (session is persisted along with session data and CSRF verification succeeds).

For those of you who are interested in some Cloud / IaC related issues, remember you have to set CloudFront's Cookies policy properly. Here is some Terraform documentation about this.

Back to Top