我对 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
我的设置.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
编辑2:
我在视图中添加了一行,现在它如下所示:
@api_view(['GET'])
def logToken(request):
return HttpResponse(request.user)
它有效,但我不知道为什么?