2

I've never developed Chrome extensions before and currently working on the Chrome extension (with link submission functionality) for my Django-powered app. When I try to submit a link using the extension I get the following error:

'POST http://127.0.0.1:8000/add_link_from_extension 403 (FORBIDDEN)'

This can be solved by passing csrfmiddlewaretoken in the postdata JSON, however, obviously I can't do

<script>var csrfmiddlewaretoken = "{{ csrf_token }}"</script>

in the html file from Chrome extension. How would you pass csrf_token from Django to Chrome extension's JavaScript? Alternatively, is there any other way around this issue? Here's the relevant portion of the JS code from the Chrome extension:

postdata = {
        "url":url.value
        //"csrfmiddlewaretoken": csrfmiddlewaretoken 
    };
$.post('http://' + "127.0.0.1:8000" + '/add_link_from_extension', postdata, success);
Arman
  • 1,074
  • 3
  • 20
  • 40

1 Answers1

5

You can try to set a cookie with the CSRF token (see: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax). Or, simply decorate your view with csrf_exempt.

Personally, I find both methods sub-optimal. Really, if you're going to allow external access to your site through something like a browser extention, you should set up and use an API, and in particular, if you're going to allow any sort of write access, you should add an authentication layer with something like OAuth. django-tastypie is a good drop-in API solution you can try, and it supports OAuth out of the box.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • Thanks! Tried csrf_exempt, still getting the same error. Will try my teeth against django-tastypie. – Arman Jul 23 '12 at 22:02
  • Any specific examples how setting a cookie with the CSRF token can be done? The django docs and http://stackoverflow.com/questions/7474988/authentication-using-chrome-extension-and-django are not clear. – Arman Jul 23 '12 at 22:46