Django:未提供身份验证凭据

时间:2018-12-27 19:07:22

标签: python ajax django authentication django-rest-framework

关于这个主题,我已经搜集了十几个类似的SO帖子,并且以我所理解的最好的方式实施了他们的解决方案,但是它们对我没有用。 为什么在使用AJAX补丁请求命中Django Rest Framework端点后出现此错误 detail: "Authentication credentials were not provided."感谢您的帮助!

一些详细信息

  • 标题告诉我“状态码:401未经授权”
  • 我在localHost开发服务器(Postgres)上
  • 在此应用程序内其他应用程序上运行的其他任何django表单或ajax(获取和发布)请求中,我均未收到此错误。
  • 这是我第一次尝试PATCH请求
  • 最终,一旦这个Ajax补丁请求生效,我只想向bookid模型中的ManyToManyField books字段添加api.BookGroup
  • 我尝试遵循类似文章中的建议,这些建议建议调整settings.py以允许使用正确的身份验证和权限方法。
  • 参考the DRF documentation,我还将权限类更​​改为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',
)
}

2 个答案:

答案 0 :(得分:1)

一旦您的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/

答案 1 :(得分:0)

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>的标头中。