python - Django:未提供身份验证凭据
问题描述
我已经提出了十几个关于这个主题的类似 SO 帖子,并且已经按照我理解的最好的方式实施了他们的解决方案,但它们并没有为我工作。为什么 detail: "Authentication credentials were not provided."
在使用 AJAX Patch 请求访问我的 Django Rest Framework 端点后出现此错误?我感谢您的帮助!
一些细节
- 标题告诉我“状态代码:401 未经授权”
- 我在我的 localHost 开发服务器(Postgres)上
- 在此应用程序中的其他应用程序上运行的任何其他 django 表单或 ajax(Get 和 Posts)请求都不会出现此错误。
- 这是我第一次尝试 PATCH 请求
- 最终,一旦这个 Ajax Patch 请求有效,我只想添加到模型
bookid
中的 ManyToManyFieldbooks
字段api.BookGroup
- 我尝试遵循类似帖子中的建议,这些建议建议调整 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)
视图.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',
)
}
解决方案
一旦您的 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/
推荐阅读
- node.js - 如何在文件夹中创建连接(mongodb)
- php - Wordpress 主题自定义文件位置
- jquery - 如何使 div 可点击?
- laravel - 使用表单集合访问 Laravel 中不同表单的输入
- collections - Directus - M2M 集合的权限
- javascript - Pie chart on tooltip hover on multi bar chart nvd3
- javascript - 弹出窗口中的 geoJSON 属性“未定义”
- android - 计算我手机上的应用程序打开了多少次
- http-post - 对 Teams MessageCard 上的“HTTPPost”操作进行身份验证以通过 Azure 应用代理调用 API
- python - 如果它们具有一定百分比的 NaN 值,则返回列(Python)