10

I am calling obtain.auth_token from urls as follows

url(r'^api-token/','rest_framework.authtoken.views.obtain_auth_token')

I get back

{
detail: "CSRF Failed: CSRF token missing or incorrect."
}

I am wondering why this happends as I was under the impression django-rest-framework was usualy CSRF exempt

Thanks

karthikr
  • 97,368
  • 26
  • 197
  • 188
user155813
  • 155
  • 9

4 Answers4

2

That view uses a POST. DRF always requires CSRF for session-authenticated POST's.

Sensitive requests like getting an auth token should use POST for just this reason.

paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
2

I had the exact same issue. Check if you have sign out of the browser.

Ryu_hayabusa
  • 3,666
  • 2
  • 29
  • 32
2

I just ran into this too. Adding an answer in case this was unclear to anyone else.

  1. Make sure you're not requesting in a context where you're already signed in, e.g. from the browser (log out, try in incognito mode, or clear your cookies if you are).
  2. Make sure you're actually using the api-token endpoint correctly. I was initially trying to use Basic Auth, assuming this token-generating view was protected, but DRF actually expects form data containing username and password fields instead.

Here's a working example using requests:

r = requests.post('http://example.com/api-token/'), data={
    'username': username,
    'password': password,
})
token = r.json()['token']
Joe
  • 16,328
  • 12
  • 61
  • 75
  • 1
    Just for future reference: "Note that the default obtain_auth_token view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the obtain_auth_token view, you can do so by overriding the ObtainAuthToken view class, and using that in your url conf instead." at http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication – MariusSiuram Jan 02 '16 at 09:48
  • @MariusSiuram Thanks for the heads up! – Joe Jan 02 '16 at 18:29
0

In order with the documentation http://www.django-rest-framework.org/topics/ajax-csrf-cors/ you have to implement ajax-csrf how is explanied in https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

... if you are using angularjs you can check it Django csrf token + Angularjs

Community
  • 1
  • 1
Javier Gutierrez
  • 549
  • 5
  • 16