簡體   English   中英

Django,DRF令牌認證不起作用,獲取匿名用戶

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM