【问题标题】:Authentication credentials were not provided - Django未提供身份验证凭据 - Django
【发布时间】:2019-06-11 08:38:09
【问题描述】:

我遇到了这个错误。尝试了几乎所有可用的解决方案,但对我没有任何帮助。在前端,我使用的是 Angular 6,我很确定这不是错误。希望尽快回复,并在此先感谢各位。

注册/url.py

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


router = routers.DefaultRouter()
router.register('users', views.UserViewSet)


# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path('', include(router.urls)),
    #path('auth/', include('rest_framework.urls', namespace='rest_framework')),
    path('auth/', ObtainAuthToken.as_view()),
]

serialier.py

from django.contrib.auth.models import User
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password')
        extra_kwargs = { 'password' : { 'write_only' : True , 'required':True } }

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user

view.py

from django.contrib.auth.models import User
from rest_framework import viewsets
from .serializers import UserSerializer
from rest_framework.permissions import IsAuthenticated



class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    authentication_classes = (TokenAuthentication, SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)

setting.py

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

浏览器控制台显示如下错误:

{“detail”:“未提供身份验证凭据。”}

【问题讨论】:

  • 改进格式、标题和问题措辞

标签: django-rest-framework


【解决方案1】:

您的视图集具有IsAuthenticated 权限类。换句话说,用户必须经过身份验证才能检索、更新甚至创建实例。确保您的请求中包含适当的标头。

例如,对于令牌身份验证,如Django Rest Framework documentation 所述

对于客户端进行身份验证,令牌密钥应包含在 授权 HTTP 标头。键应以字符串文字为前缀 “令牌”,用空格分隔两个字符串。例如:

Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

在创建帐户的特定情况下,我不确定您的应用程序是否需要用户身份验证。

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 2019-05-25
    • 2017-11-22
    • 2015-05-16
    • 2019-04-29
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    相关资源
    最近更新 更多