[英]DRF can't authorize account via token, always getting anonymous user object
[英]Django, DRF Token authentication doesn't work, get Anonymous User
我是Django的新手。 我想为手机做一些授权。 我已阅读以下文档: http : //www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme尽管我已经阅读并完成了它的编写工作,但它并没有工作。 我已经为一个用户获得了一个令牌,但是当我想使用该令牌进行身份验证时,没有结果,我得到了AnonymousUser。
{"token": "e2a9b561fc24a65b607135857d304747a36d0e8d"}
curl -X GET http://<ip:port>/trainer/logToken/ -H "Authorization: Token e2a9b561fc24a65b607135857d304747a36d0e8d"
结果是:
AnonymousUser
我的settings.py:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'trainer',)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
)
视图:
def logToken(request):
return HttpResponse(request.user)
有任何想法吗? 我尝试使用基本身份验证登录,但也没有结果
编辑:当我执行:
curl -viL -H "Authorization: Token e2a9b561fc24a65b607135857d304747a36d0e8d" http://<ip:port>/trainer/logToken/
我得到:
* About to connect() to <IP> port 8000 (#0)
* Trying <IP>...
* Adding handle: conn: 0x25b82c0
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x25b82c0) send_pipe: 1, recv_pipe: 0
* Connected to <IP> (<IP>) port 8000 (#0)
> GET /trainer/logToken/ HTTP/1.1
> User-Agent: curl/7.30.0
> Host: <IP>:8000
> Accept: */*
> Authorization: Token e2a9b561fc24a65b607135857d304747a36d0e8d
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
HTTP/1.0 200 OK
< Date: Thu, 26 Nov 2015 20:52:36 GMT
Date: Thu, 26 Nov 2015 20:52:36 GMT
< Server: WSGIServer/0.2 CPython/3.4.2
Server: WSGIServer/0.2 CPython/3.4.2
< X-Frame-Options: SAMEORIGIN
X-Frame-Options: SAMEORIGIN
< Content-Type: text/html; charset=utf-8
Content-Type: text/html; charset=utf-8
< Vary: Cookie
Vary: Cookie
<
AnonymousUser* Closing connection 0
默认情况下添加以下行
django.contrib.auth.middleware.AuthenticationMiddleware to your MIDDLEWARE_CLASSES
EDIT2:
我在视图中添加了一行,现在看起来如下:
@api_view(['GET'])
def logToken(request):
return HttpResponse(request.user)
可以,但是我不知道为什么?
没有api_view
装饰器,它是常规的Django视图。 DRF嵌入了自己的身份验证和权限系统,以免发生诸如要求CSRF之类的事情,即使您以JSON形式发布数据。
相对的部分是DRF扩展了APIView
的Django请求,在APIView
执行身份验证,授权,限制和其他一些操作。 请注意, api_view
装饰器将api_view
封装在APIView
周围。
因此,使用装饰器,您将使DRF系统处于活动状态,而没有DRF系统将无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.