[Solved]-Django Sessions are not maintaing in an iframe

5👍

This has little to do with django. Browsers are currently paranoid about giving frames/embeds access to cookies, even when they are the source of the cookie. In addition, many users block third-party cookies (which usually includes frame cookies), or all cookies. You could embed a session id in the frame source, as this answer suggests, with the session id generated (either completely random or from cookie) by django template or client-side javascript on the page that contains the frame which might have access to the cookie.

You may also want to look into dropping the embed/frame entirely in favor of a django include block, which inserts the chat content window into the containing page as a div or similar, therefor giving greater access to cookies or other session variables. In this case I’d separate the javascript from the html and put the js script tag in the head.

As a last-ditch shot, you could replace the dependency on cookies with a combination of the client’s public ip and user-agent, and maybe the containing-pages URI (in the case of a template).

Edit With regard to security: (after a comment by @EthanKeller)

Browsers try to protect frames from main content and vice versa. It all depends on rather either contains any sensitive info. If so, then I suggest separating them by putting the frame in it’s own window/tab, potentially via popup call. In the case of a chatbot, however, I doubt there is anything all that sensitive. Dealer’s choice.

👤memtha

5👍

To allow cookies from an iframe, you have to set your cookie using SameSite=None and Secure options.

Set-Cookie: session=your_session; SameSite=None; Secure 

Source: https://medium.com/trabe/cookies-and-iframes-f7cca58b3b9e

To do this with Django, you’ll have to update the following settings:

SESSION_COOKIE_SAMESITE = 'None'  # As a string
SESSION_COOKIE_SECURE = True

Unfortunately, 'None' value for SESSION_COOKIE_SAMESITE is only available since Django 3.1 and there is no plan to backport it in 3.0 and 2.2.

Also note that your website has to be served over HTTPS.

Leave a comment