简体   繁体   中英

Django forms with CSRF protection in IOS 14+

IOS 14 came out a few months ago, which defaults to blocking all third party cookies unless the user enables them specifically by disabling this option:

Settings -> Safari -> Prevent Cross-site Tracking

This presents a problem for Django forms with csrf protection that is served inside an <iframe> from a third-party domain like this:

-----Parent website-----
|                       |
|   -----------------   |
|   |               |   |
|   |  Django form  |   |
|   |    inside     |   |
|   |    iframe     |   |
|   |               |   |
|   -----------------   |
|                       |
-------------------------

Django form sets a csrfmiddlewaretoken as a hidden form variable and also sets a cookie called csrftoken , and does the form security verification when the form is submitted.

The problem comes when attempting to set the cookie csrftoken while inside an <iframe> , being in a third-party website context. In IOS 14, this cookie is rejected. The form still submits without this cookie but Django rejects the form as expected.

The exact error I am getting: Forbidden (CSRF cookie not set.) , which is correct from Django's point of view.

The form works correctly when we disable the Safari setting, to allow cross-site tracking. But this needs to be done at the user level, which is not practical. The form also works correctly when being served directly in a new browser window.

Now, here are my options:

  1. Disable csrf security in my form as explained in django docs (not recommended from the security point of view)

  2. Tell users to enable third-party tracking (not possible)

There are a lot of references online about Django forms and IOS that are related to issues with the SameSite: None setting, but I can't find a solution to this new IOS 14 problem for enabling non-tracking cookies inside iframes. Has anyone found a solution to this problem yet?

It's a hard constraint for third party web pages loaded inside iframes in IOS browser. There is nothing that can be done to overcome this cookie limitation. Given that IOS is doing it, there is a chance that other browser vendors may also follow this practice in future.

For now, the only way is to exempt CSRF for django forms that are expected to run inside iframes.

More details to exempt CSRF in forms: https://docs.djangoproject.com/en/3.2/ref/csrf/#django.views.decorators.csrf.csrf_exempt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM