DRF 和 axios - 令牌身份验证不使用 axios 返回令牌,但使用 curl 返回令牌



如果我运行这个curl命令,它可以工作:

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

但是,如果我使用 axios 执行以下操作,它会失败并返回401

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)
})

来自服务器的响应:

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

我做错了什么?

编辑:此外,这个 axios 请求正在 vueJS 项目上完成

编辑这是Chrome Dev工具的"网络"选项卡在通过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/

我想通了(经过一整天的调试...

问题在于,TokenAuthenticationDEFAULT_AUTHENTICATION_CLASS甚至阻止了axiosPOST请求被调用。因为我的axios调用在标头中不包含令牌(因为...它试图获得一个令牌(TokenAuthentication类会立即拒绝它,使用 401 代码。

所以我所做的是创建一个自定义SFObtainAuthToken类,该类对 DRFObtainAuthToken进行子类化,但我用一个空authentication_class([])装饰它。然后,当我将api/token-auth/URL连接到我的自定义SFObtainAuthToken时,它将允许请求,因为没有绑定的身份验证类。

希望这有助于其他人在这个问题上:)

网址

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

自定义获取身份验证令牌类

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)

姜戈设置

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

最新更新