DRF和axios-令牌验证不使用axios返回令牌,但是使用curl [英] DRF & axios - token auth not returning token with axios, but does with curl

查看:132
本文介绍了DRF和axios-令牌验证不使用axios返回令牌,但是使用curl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行此curl命令,它将起作用:

If I run this curl command, it works:

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

但是,如果我对axios执行以下操作,它将失败并返回401:

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

来自服务器的响应:

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

我在做什么错了?

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

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

编辑,这是通过axios进行请求时Chrome Dev工具的网络"标签上显示的内容:

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/

推荐答案

我弄清楚了(经过一整天的调试...):

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

问题是TokenAuthenticationDEFAULT_AUTHENTICATION_CLASS阻止了甚至调用axios POST的请求.因为我的axios调用在标头中不包含令牌(因为...正在尝试获取令牌),所以TokenAuthentication类将立即使用401代码拒绝它.

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.

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

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

网址

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

自定义ObtainAuthToken类

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设置

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

这篇关于DRF和axios-令牌验证不使用axios返回令牌,但是使用curl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆