簡體   English   中英

令牌身份驗證不適用於 Django Rest 框架

[英]Token Authentication Not Working on Django Rest Framework

我有一個 Django 應用程序,我將 DRF 用於我的具有會話和令牌身份驗證的 API。 我安裝的應用程序中有 rest_framework 和 rest_framework.authtoken。 我已經遷移了我的數據庫,可以在 Django 管理中為用戶創建令牌。 我知道所有這些都有效,因為我正在訪問 rest_framework.auth_token 的 obtain_auth_token 視圖,以便在 POST 請求中提交用戶數據時返回一個令牌,並收到一個返回。 當我嘗試向我的應用程序中的視圖函數發出 GET 請求時,它的視圖集上有 TokenAuthentication,它一直在返回。

{"detail":"Authentication credentials were not provided."}

設置文件

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # My Apps
    'rest_framework',
    'rest_auth',
    'rest_framework.authtoken',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
}

網址

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken import views

from api.views.some_model import MyViewSet

urlpatterns = [
    path('', include(router.urls)),
    path('rest-auth/', include('rest_auth.urls')),
    path('api-token-auth/', views.obtain_auth_token)
]

視圖集

from rest_framework.viewsets import ModelViewSet
from rest_framework.authentication import SessionAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated

from some_app.models import SomeModel
from api.serializers.exams import SomeModelSerializer


class ExamViewSet(ModelViewSet):
    permission_classes = (IsAuthenticated,)
    authentication_classes = (TokenAuthentication, SessionAuthentication)

    queryset = SomeModel.objects.all()
    serializer_class = SomeModelSerializer

獲取響應的 Python 腳本

import requests
import json

data = {
    "username": "myemail@gmail.com",
    "password": "password124"
}
url = "http://localhost:8002/api/v1/api-token-auth/"
response = requests.post(url, data=data)
token = json.loads(response.text).get('token')

if token:
    token = f"Token {token}"
    headers = {"Authentication": token}
    response = requests.get("http://localhost:8002/api/v1/model/", headers=headers)
    print(response.text)
else:
    print('No Key')

標頭名稱應為“ Authorization而非Authentication

headers = {"Authorization": token}
response = requests.get("http://localhost:8002/api/v1/model/", headers=headers)

令牌應在標頭中提供,例如

 -H  "Authorization: Token 8fa36c01df3bb9ed31fc2329c53a9fe2cac72966"

授權:前綴YourToken

如果您使用的是 JWT 身份驗證,那么您的請求標頭應該如下所示

授權: JWT your-token-here

要么

授權:在這里持有你的令牌

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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