Cross domain cookie to extract csrf token

678 views
Skip to first unread message

Luther Goh Lu Feng

unread,
Apr 21, 2012, 2:57:41 PM4/21/12
to Django users
I am running a website on local host (my mac, ip 127.0.0.1) and my
django dev server on a VM (some other ip eg. 192.168.56.1).

I load up the local host website, which 'emulates' the mobile app that
I will build using phonegap. I am issuing ajax requests from the
website to the django application residing in the VM.

The views that the requests are routed to are not csrf exempt. As
such, I issue a get request on the local website to try and obtain the
csrf token:

$.get('http://127.0.0.1:8000/login')

In the response headers, the following is returned:
Set-Cookie:csrftoken=82c34b2495ad0c7f8a5fed67ca9a21bd; expires=Sat, 20-
Apr-2013 05:20:20 GMT; Max-Age=31449600; Path=/

However, this is unfortunately not found in document.cookie.

I would like to ask for advice on how I can get around this problems.


Thanks in advance,

Luther

Luther Goh Lu Feng

unread,
Apr 23, 2012, 6:04:11 AM4/23/12
to Django users
I have managed to resolve the issue. This only works on phonegap,
chrome 20 but not on desktop safari 5.1.5.

General strategy:
- Make an ajax OPTIONS call to http://foo
- Generate the csrf token and return it in the success callback
- Extract the csrf token
- In the success callback do the ajax post, and set the request header
with the csrf token using xhr.setRequestHeader("X-CSRFToken", token)
- In the middleware you will need to enable CORS and accept the
csrftoken headder

Desktop safari seemed to fail as it was unable to return the cookie in
the ajax post call

This is in django 1.4 and with the view decorators:

@ensure_csrf_cookie
@require_http_methods(["OPTIONS", "POST"])

Luther Goh Lu Feng

unread,
Apr 24, 2012, 3:56:12 AM4/24/12
to Django users
If for whatever reason you are using django 1.3, you need to ensure
the csrf token generated in the view is passed through unicode. eg
unicode(csrf(request)['csrf_token'])

On Apr 23, 6:04 pm, Luther Goh Lu Feng <elf...@yahoo.com> wrote:
> I have managed to resolve the issue. This only works on phonegap,
> chrome 20 but not on desktop safari 5.1.5.
>
> General strategy:
> - Make an ajax OPTIONS call tohttp://foo
Reply all
Reply to author
Forward
0 new messages