2

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.

jedierikb
  • 12,752
  • 22
  • 95
  • 166

1 Answers1

2

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

jedierikb
  • 12,752
  • 22
  • 95
  • 166
rockingskier
  • 9,066
  • 3
  • 40
  • 49
  • v interesting idea, but are there security precautions that need to be taken into account using csrf as a url parameter in the 1st place? – jedierikb May 02 '13 at 15:20
  • 1
    TBH I'm not sure, according to http://stackoverflow.com/a/198473/682968 GET and POST have the same level of security so its really no different to POSTing a form 'normally'. Also the csrf token is freely available in the page source as well so anyone could read it there too. – rockingskier May 02 '13 at 15:25
  • 1
    @rockingskier: The answer you are referring to was accepted, but gained more than 3 times fewer votes than some other answer (http://stackoverflow.com/a/1744404/548696), not without a reason. – Tadeck May 06 '13 at 23:30
  • @Tadeck, so it did, thanks for pointing to the better answer. – rockingskier May 07 '13 at 08:40