首页 > 解决方案 > Django:未提供身份验证凭据

问题描述

我已经提出了十几个关于这个主题的类似 SO 帖子,并且已经按照我理解的最好的方式实施了他们的解决方案,但它们并没有为我工作。为什么 detail: "Authentication credentials were not provided."在使用 AJAX Patch 请求访问我的 Django Rest Framework 端点后出现此错误?我感谢您的帮助!

一些细节

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)

视图.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...")

设置.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',
)
}

标签: pythonajaxdjangoauthenticationdjango-rest-framework

解决方案


一旦您的 API 视图需要身份验证才能访问,您需要向请求的标头提供 Authorization 标头: Authorization: Token <token>

那么,如何获得这个 Token?根据 DRF 文档,您需要为数据库中的每个用户创建一个令牌。因此,每当创建新用户时,您都必须手动执行操作,或者您可以通过导入和使用来使用 DRF 令牌身份验证视图:

from rest_framework.authtoken.views import ObtainAuthToken

但我建议你使用 django-rest-auth 应用程序,它使 DRF 中的 Token 身份验证过程更容易。 https://django-rest-auth.readthedocs.io/en/latest/


推荐阅读