Django,DRF Token身份验证不起作用,获取匿名用户

时间:2015-11-26 20:34:36

标签: python django django-rest-framework http-token-authentication

我对Django很新。我想为移动设备做一些授权。我已阅读以下文档: executionWindow 虽然我已经阅读并完成了它的全面写作,但它不起作用。 我已经为一个用户获取了一个令牌,但是当我想使用此令牌进行身份验证时,没有结果,我得到了AnonymousUser。

AnonymousUser

结果:

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',
)

我的settings.py:

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

默认情况下会添加以下行

@api_view(['GET'])
def logToken(request):
    return HttpResponse(request.user)

EDIT2:

我在视图中添加了一行,现在看起来如下:

string[]

它有效,但我不明白为什么?

1 个答案:

答案 0 :(得分:2)

没有api_view装饰器,它是一个常规的Django视图。 DRF嵌入了自己的身份验证和权限系统,以避免即使您使用JSON发布数据也需要CSRF。

计数器部分是DRF在执行身份验证,授权,限制和其他一些事情的APIView中扩展Django请求。请注意,api_view装饰器会在您的函数周围包裹APIView

因此,使用装饰器,您将使DRF系统处于活动状态,而不会让它简单地工作。

相关问题