DRF & axios - token auth not returning token with

2019-06-10 20:28发布

问题:

If I run this curl command, it works:

-> curl -X POST http://localhost:8000/api/token-auth/ --data "username=garfonzo&password=garfonzo"
-> {"token":"79b2428019994713d61bb2f728ae62ae8c8be9ee"}%

But if I do the following with axios, it fails with a 401 returned:

const API_URL = 'http://localhost:8000/api/'
const LOGIN_URL = API_URL + 'token-auth/'

// "creds" in this situation is a dict of { username: 'garfonzo', password: 'garfonzo' }
axios.post(LOGIN_URL, creds).then((response) => {
  localStorage.setItem('token', response.data.token)
  this.user.authenticated = true

  // If a redirect link is provided
  if (redirect) {
    router.push(redirect)
  }
}).catch((err) => {
  console.log(err)
})

Response from server:

->"POST /api/token-auth/ HTTP/1.1" 401 27

What am I doing wrong?

Edit: Also, this axios request is being done on a vueJS project

EDIT This is what the Network tab of the Chrome Dev tools shows when doing the request via axios:

Request URL:http://localhost:8000/api/token-auth/
Request Method:POST
Status Code:401 Unauthorized
Remote Address:127.0.0.1:8000
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Origin:*
Allow:POST, OPTIONS
Content-Type:application/json
Date:Wed, 23 Aug 2017 19:18:00 GMT
Server:WSGIServer/0.1 Python/2.7.12
WWW-Authenticate:Token
X-Frame-Options:SAMEORIGIN
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Authorization:Token null
Connection:keep-alive
Content-Length:27
Content-Type:application/x-www-form-urlencoded;charset=UTF-8
Host:localhost:8000
Origin:http://localhost:8080
Referer:http://localhost:8080/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36
Form Data
view source
view URL encoded
username:garfonzo
password:garfonzo
Name
jquery-3.1.1.slim.min.js
bootstrap.min.js
vee-validate.js
app.js
?is_brokerage=false
themify.a1ecc3b.woff
__webpack_hmr
token-auth/

回答1:

I figured it out (after a whole day of debuggin...):

The problem was that the DEFAULT_AUTHENTICATION_CLASS of TokenAuthentication was preventing the axios POST request of even being called. Because my axios call didn't contain a token in the header (since... it's trying to get a token) the TokenAuthentication class would reject it immediately, with the 401 code.

So what I did was create a custom SFObtainAuthToken class that subclasses the DRF ObtainAuthToken but I decorate it with an empty authentication_class([]). Then when I wire up the api/token-auth/ URL to my custom SFObtainAuthToken, it will allow the request since there are no authentication classes tied to it.

Hope this helps someone else stuck on this issue :)

urls

url(r'^api/token-auth/', SFObtainAuthToken.as_view())

Custom ObtainAuthToken Class

from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.decorators import authentication_classes, permission_classes

@authentication_classes([])
class SFObtainAuthToken(ObtainAuthToken):
    def post(self, request, *args, **kwargs):
        return super(SFObtainAuthToken, self).post(request, *args, **kwargs)

Django Settings

# DRF Auth stuff
REST_FRAMEWORK = {
  'DEFAULT_FILTER_BACKENDS': (
    'django_filters.rest_framework.DjangoFilterBackend',
  ),
  'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
  ),
}