Search code examples
djangoiframesecuritycsrf

passing CSRF credentials as url parameters?


How do you handle csrf credentials sent to django as url parameters?

I ask because that is, evidently, the only way to submit a file upload via a form in an iFrame.

Most online examples show to pass csrf credentials as headers,

xhr.setRequestHeader("X-CSRFToken", csrfToken );

but this is not an option for iFrame transport in ie/opera.

I can use csrf_exempt, but this leaves my site vulnerable.


Solution

  • You could create some middleware that takes csrf_token from the GET params and places it on the request before CsrfViewMiddleware attempts to validate

    class CsrfGetParamMiddleware(object):
        def process_request(self, request):
            request.META['HTTP_X_CSRFTOKEN'] = request.GET.get('csrf_token')
            return None
    

    Place this middleware above the CsrfViewMiddleware

    MIDDLEWARE_CLASSES = (
        'CsrfGetParamMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
    )
    

    This save you from validating it yourself or subclassing CsrfViewMiddleware