简体   繁体   English

Django Rest 框架 - 未提供身份验证凭据

[英]Django Rest Framework - Authentication credentials were not provided

I'm developing an API using Django Rest Framework.我正在使用 Django Rest 框架开发 API。 I'm trying to list or create an "Order" object, but when i'm trying to access the console gives me this error:我正在尝试列出或创建一个“订单”object,但是当我尝试访问控制台时出现此错误:

{"detail": "Authentication credentials were not provided."}

Views:意见:

from django.shortcuts import render
from rest_framework import viewsets
from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer, YAMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from order.models import *
from API.serializers import *
from rest_framework.permissions import IsAuthenticated

class OrderViewSet(viewsets.ModelViewSet):
    model = Order
    serializer_class = OrderSerializer
    permission_classes = (IsAuthenticated,)

Serializer:序列化器:

class OrderSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Order
        fields = ('field1', 'field2')

And my URLs:还有我的网址:

# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.utils.functional import curry
from django.views.defaults import *
from rest_framework import routers
from API.views import *

admin.autodiscover()

handler500 = "web.views.server_error"
handler404 = "web.views.page_not_found_error"

router = routers.DefaultRouter()
router.register(r'orders', OrdersViewSet)

urlpatterns = patterns('',
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'),
    url(r'^api/', include(router.urls)),
)

And then I'm using this command in the console:然后我在控制台中使用这个命令:

curl -X GET http://127.0.0.1:8000/api/orders/ -H 'Authorization: Token 12383dcb52d627eabd39e7e88501e96a2sadc55'

And the error say:错误说:

{"detail": "Authentication credentials were not provided."}

If you are running Django on Apache using mod_wsgi you have to add如果您使用 mod_wsgi 在 Apache 上运行 Django,您必须添加

WSGIPassAuthorization On

in your httpd.conf .在您的httpd.conf Otherwise, the authorization header will be stripped out by mod_wsgi .否则,授权标头将被mod_wsgi剥离。

Solved by adding "DEFAULT_AUTHENTICATION_CLASSES" to my settings.py通过将“DEFAULT_AUTHENTICATION_CLASSES”添加到我的 settings.py 来解决

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (
       'rest_framework.authentication.TokenAuthentication',
   ),
   'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAdminUser'
   ),
}

This help me out without "DEFAULT_PERMISSION_CLASSES" in my settings.py这可以帮助我在我的 settings.py 中没有“DEFAULT_PERMISSION_CLASSES”

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'PAGE_SIZE': 10
}

Just for other people landing up here with same error, this issue can arise if your request.user is AnonymousUser and not the right user who is actually authorized to access the URL.只是对于其他人登陆这里有同样的错误,如果您的request.userAnonymousUser而不是实际有权访问 URL 的正确用户,则可能会出现此问题。 You can see that by printing value of request.user .您可以通过打印request.user的值来查看。 If it is indeed an anonymous user, these steps might help:如果确实是匿名用户,这些步骤可能会有所帮助:

  1. Make sure you have 'rest_framework.authtoken' in INSTALLED_APPS in your settings.py .确保在settings.pyINSTALLED_APPS中有'rest_framework.authtoken'

  2. Make sure you have this somewhere in settings.py :确保你在settings.py的某个地方有这个:

     REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', # ... ), # ... }
  3. Make sure you have the correct token for the user who is logged in. If you do not have the token, learn how to get it here .确保您拥有登录用户的正确令牌。如果您没有令牌,请在此处了解如何获取它。 Basically, you need to do a POST request to a view which gives you the token if you provide the correct username and password.基本上,如果您提供正确的用户名和密码,您需要向一个视图发出POST请求,该视图会为您提供令牌。 Example:例子:

     curl -X POST -d "user=Pepe&password=aaaa" http://localhost:8000/
  4. Make sure the view which you are trying to access, has these:确保您尝试访问的视图具有以下内容:

     class some_fancy_example_view(ModelViewSet): """ not compulsary it has to be 'ModelViewSet' this can be anything like APIview etc, depending on your requirements. """ permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) # ...
  5. Use curl now this way:现在以这种方式使用curl

     curl -X (your_request_method) -H "Authorization: Token <your_token>" <your_url>

Example:例子:

    curl -X GET http://127.0.0.1:8001/expenses/  -H "Authorization: Token 9463b437afdd3f34b8ec66acda4b192a815a15a8"

If you are playing around in the command line (using curl, or HTTPie etc) you can use BasicAuthentication to test/user your API如果您在命令行中玩耍(使用 curl 或 HTTPie 等),您可以使用 BasicAuthentication 来测试/使用您的 API

    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.IsAuthenticated',
        ],
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.BasicAuthentication',  # enables simple command line authentication
            'rest_framework.authentication.SessionAuthentication',
            'rest_framework.authentication.TokenAuthentication',
        )
    }

You can then use curl然后你可以使用curl

curl --user user:password -X POST http://example.com/path/ --data "some_field=some data"

or httpie (its easier on the eyes):httpie (它更容易对眼睛):

http -a user:password POST http://example.com/path/ some_field="some data"

or something else like Advanced Rest Client (ARC)或其他类似Advanced Rest Client (ARC)

I too faced the same since I missed adding我也面临同样的问题,因为我错过了添加

authentication_classes = (TokenAuthentication) authentication_classes = (TokenAuthentication)

in my API view class.在我的 API 视图类中。

class ServiceList(generics.ListCreateAPIView):
    authentication_classes = (SessionAuthentication, BasicAuthentication, TokenAuthentication)
    queryset = Service.objects.all()
    serializer_class = ServiceSerializer
    permission_classes = (IsAdminOrReadOnly,)

In addition to the above, we need to explicitly tell Django about the Authentication in settings.py file.除了上述之外,我们还需要在 settings.py 文件中明确告诉 Django Authentication

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (
   'rest_framework.authentication.TokenAuthentication',
   )
}

For me, I had to prepend my Authorization header with "JWT" instead of "Bearer" or "Token" on Django DRF.对我来说,我必须在 Django DRF 上使用“JWT”而不是“Bearer”或“Token”来添加我的 Authorization 标头。 Then it started working.然后它开始工作。 eg -例如 -

Authorization: JWT asdflkj2ewmnsasdfmnwelfkjsdfghdfghdv.wlsfdkwefojdfgh

I was having this problem with postman.Add this to the headers...我遇到了邮递员的问题。将其添加到标题中... 在此处输入图像描述

Adding SessionAuthentication in settings.py will do the jobsettings.py中添加SessionAuthentication将完成这项工作

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': ( 
        'rest_framework.authentication.SessionAuthentication',
    ),
}

Try this, it worked for me.试试这个,它对我有用。

In settings.py在 settings.py

SIMPLE_JWT = {
     ....
     ...
     # Use JWT 
     'AUTH_HEADER_TYPES': ('JWT',),
     # 'AUTH_HEADER_TYPES': ('Bearer',),
     ....
     ...
}

Add this too也加这个

REST_FRAMEWORK = {
    ....
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
    ...
    ..
}

由于它是会话登录,因此您需要提供凭据,因此127.0.0:8000/admin admin 并稍后登录它会正常工作

如果您使用的是authentication_classes ,那么您应该在User模型中将is_activeTrue ,默认情况下可能为False

Also make sure that the Authorization Token / API key is actually valid.还要确保授权令牌/API 密钥实际上是有效的。 The Authentication credentials were not provided. Authentication credentials were not provided. error message seems to be what's returned by the API if the key is invalid as well (I encountered this when I accidently used the wrong API key).如果密钥也无效,错误消息似乎是 API 返回的内容(当我不小心使用了错误的 API 密钥时遇到了这个问题)。

if anyone come here from Full Stack React & Django [5] - Django Token Authentication - Traversy Media So you need to something like this如果有人来自Full Stack React & Django [5] - Django Token Authentication - Traversy Media所以你需要这样的东西

accounts/api.py帐户/api.py

from rest_framework import generics, permissions
from rest_framework.response import Response
from knox.models import AuthToken
from .serializers import LoginSerializer, RegisterSerializer, UserSerializer
from knox.auth import TokenAuthentication

# Register Api


class RegisterAPI(generics.GenericAPIView):
    serializer_class = RegisterSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)[1]
        })

# Login Api


class LoginAPI(generics.GenericAPIView):
    serializer_class = LoginSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data
        return Response({
            "user": UserSerializer(user, context=self.get_serializer_context()).data,
            "token": AuthToken.objects.create(user)[1]
        })

# Get User Api


class UserAPI(generics.RetrieveAPIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = [
        permissions.IsAuthenticated,
    ]

    serializer_class = UserSerializer

    def get_object(self):
        return self.request.user

如果您使用的是 CDN,请检查 CDN 是否在将请求转发到您的服务器时不会删除请求标头。

In my case TokenAuthentication was missing在我的例子中,TokenAuthentication 丢失了

@authentication_classes([SessionAuthentication, BasicAuthentication])

I changed it to below and it worked我将其更改为以下并且有效

@authentication_classes([SessionAuthentication, BasicAuthentication, TokenAuthentication])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django Rest Framework JWT“未提供身份验证凭据。”} - Django Rest Framework JWT “Authentication credentials were not provided.”} Django Rest Framework {“detail”:“未提供身份验证凭据。”} - Django Rest Framework {“detail”:“Authentication credentials were not provided.”} django rest 框架中未提供错误身份验证凭据 - getting error Authentication credentials were not provided in django rest framework Python 请求与 Django Rest 框架 - “详细信息”:“未提供身份验证凭据” - Python Requests with Django Rest Framework - 'detail': 'Authentication credentials were not provided' Django-rest-framework {“详细信息”:“未提供身份验证凭据。” } 使用 django-rest-knox - Django-rest-framework {“detail”: “Authentication credentials were not provided.” } using django-rest-knox 自定义Django休息框架身份验证响应{“详细信息”:“未提供身份验证凭据。”} - Customize Django rest framework authentication response {“detail”: “Authentication credentials were not provided.”} 如何在 Django rest 框架中自定义 [Authentication credentials were not provided] 错误消息 - How to customize [Authentication credentials were not provided] error message in Django rest framework Django:未提供身份验证凭据 - Django: Authentication credentials were not provided Django:“详细信息”:“未提供身份验证凭据。” - Django : “detail”: “Authentication credentials were not provided.” "detail": "未提供身份验证凭据。" Django-rest-frameweork 和 React - "detail": "Authentication credentials were not provided." Django-rest-frameweork and React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM