未提供身份验证凭据-Django

时间:2019-01-17 07:29:54

标签: django-rest-framework

我遇到此错误。尝试了几乎所有可用的解决方案,但对我没有任何帮助。在前端,我正在使用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',
]

浏览器的控制台中显示以下错误:

  

{“详细信息”:“未提供身份验证凭据。”}

1 个答案:

答案 0 :(得分:0)

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

例如,对于令牌认证,如Django Rest Framework documentation

所述
  

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

     

Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

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