簡體   English   中英

Django:未提供身份驗證憑據

[英]Django: Authentication credentials were not provided

我在這個主題上搜集了十幾個類似的SO帖子,並以我所理解的最好的方式實施了他們的解決方案,但它們並沒有為我工作。 為什么得到此錯誤 detail: "Authentication credentials were not provided." 使用AJAX修補程序請求擊中Django Rest Framework端點后? 我感謝您的幫助!

一些細節

  • 標頭告訴我“狀態碼:未經授權的401”
  • 我在我的localHost開發服務器(Postgres)上
  • 我在此應用程序內其他應用程序上運行的其他任何django表單或ajax(獲取和發布)請求中均未收到此錯誤。
  • 這是我第一次嘗試PATCH請求
  • 最終,一旦這個Ajax Patch請求bookid ,我只想將bookid添加到api.BookGroup模型中的ManyToManyField books字段中
  • 我嘗試遵循類似文章中的建議,這些建議建議調整settings.py以允許使用正確的身份驗證和權限方法。
  • 參考DRF文檔 ,我還將權限類別更改為permission_classes = (IsAuthenticated,) ,如果我在發出請求時登錄,則應允許補丁請求(是的,我肯定已登錄)
  • Ajax標頭中的表單數據顯示我正確地傳遞了CSRF令牌和適當的變量:

     csrfmiddlewaretoken: UjGnVfQTfcmkZKtWjI0m89zlAJqR0wMmUVdh1T1JaiCdyRe2TiW3LPWt bookid: 1 bookgroupid: 71 

AJAX

function AddToBookGroup(bookgroupid,bookid){
 $.ajax({
    type: "PATCH",
    url: '/api/bookgroups/'+bookgroupid+'/',
    data: {
        csrfmiddlewaretoken: window.CSRF_TOKEN,
        bookid: bookid,
        bookgroupid: bookgroupid
        }, 
    success: function(data){
        console.log( 'success, server says '+data);  
    }
 });
}

URLS.py

from django.urls import path, include
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', include(router.urls)),
    url(r'bookgroups/\d+/$', views.BookGroupUpdateSet.as_view()),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

VIEWS.py

from rest_framework.generics import ListAPIView, DestroyAPIView, UpdateAPIView, RetrieveAPIView
from rest_framework.authentication import TokenAuthentication, SessionAuthentication, BasicAuthentication
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from . import serializers, models, permissions

class BookGroupUpdateSet(UpdateAPIView):
    queryset = models.BookGroup.objects.all()
    model = models.BookGroup
    serializer_class = serializers.BookGroupUpdateSerializer

    def patch(self, request, pk=None):
        permission_classes = (IsAuthenticated,)
        authentication_classes = (TokenAuthentication,)
        bookid = request.Patch['bookid']
        bookgroupid = request.Patch['bookgroupid']
        print("...Print stuff...")

SETTINGS.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'authenticate',
    'api',
    'rest_framework',
    'rest_framework.authtoken',
]

AUTH_USER_MODEL = "api.UserProfile"

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
   'rest_framework.authentication.TokenAuthentication',
   'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
    # 'rest_framework.permissions.AllowAny',  # I've tried this too, same results
    'rest_framework.permissions.IsAuthenticated',
)
}

一旦您的API視圖要求進行身份驗證才能訪問,則需要向請求的標頭提供Authorization標頭: Authorization: Token <token>

那么,您如何獲得此令牌? 根據DRF文檔,您需要為數據庫中的每個用戶創建一個令牌。 因此,無論何時創建新用戶,您都必須手動執行操作,或者可以通過導入和使用DRF令牌認證視圖來使用:

from rest_framework.authtoken.views import ObtainAuthToken

但是我建議您使用django-rest-auth應用程序,它可以簡化DRF中的令牌身份驗證過程。 https://django-rest-auth.readthedocs.io/en/latest/

Django Rest Framework視圖中,您無需使用CSRF令牌,而可以使用自定義DRF令牌(即rest_framework.authtoken的用途)。 創建新用戶時,必須創建其令牌,如下所示:

def create(self, validated_data):
    from rest_framework.authtoken.models import Token

    try:
        user = models.User.objects.get(email=validated_data.get('email'))
    except User.DoesNotExist:
        user = models.User.objects.create(**validated_data)

        user.set_password(user.password)
        user.save()
        Token.objects.create(user=user) # -------> Token creation

        return user
    else:
        raise CustomValidation('eMail already in use', 'email', status_code=status.HTTP_409_CONFLICT)

然后,您必須為用戶獲取令牌,並將其發送到鍵名稱為Authorization且值為Token <token>的標頭中。

暫無
暫無

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

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