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

2

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

I have had to sign out, and refresh login page, then works great. Thx!
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']

2 Comments

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 django-rest-framework.org/api-guide/authentication/…
@MariusSiuram Thanks for the heads up!
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.