python - token验证 - django restful api教学




Django Rest Framework-未提供身份验证凭据 (5)

我正在使用Django Rest Framework开发API。 我正在尝试列出或创建“ Order”对象,但是当我尝试访问控制台时,出现此错误:

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

观看次数:

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,)

序列化器:

class OrderSerializer(serializers.HyperlinkedModelSerializer):

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

我的网址:

# -*- 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)),
)

然后我在控制台中使用以下命令:

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

错误说:

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

仅对于其他因相同错误登陆此处的人,如果您的 request.userAnonymousUser 而不是实际有权访问URL的正确用户,则可能会出现此问题。 您可以通过打印 request.user 值来看到。 如果确实是匿名用户,这些步骤可能会有所帮助:

  1. 确保您 'rest_framework.authtoken' 中的 INSTALLED_APPS 中具有 'rest_framework.authtoken'

  2. 确保在 settings.py 某处有此文件:

    REST_FRAMEWORK = {
    
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.TokenAuthentication',
            # ...
        ),
    
        # ...
    }
  3. 确保您具有登录用户的正确令牌。如果您没有令牌,请 here 了解如何获取令牌。 基本上,如果您提供了正确的用户名和密码,则需要向一个视图发出 POST 请求,该视图将为您提供令牌。 例:

    curl -X POST -d "user=Pepe&password=aaaa"  http://localhost:8000/
  4. 确保您尝试访问的视图具有以下内容:

    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. 现在以这种方式使用 curl

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

例:

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

在settings.py中添加SessionAuthentication就可以了

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


如果您在命令行中玩耍(使用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',
        )
    }

然后可以使用 curl

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

httpie (在眼睛上更容易):

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

或其他类似 Advanced Rest Client(ARC)的东西


我也遇到了同样的事情,因为我错过了添加

authentication_classes =(令牌认证)

在我的API视图类中。

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

除了上述内容外,我们还需要在settings.py文件中向Django明确告知 Authentication

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

通过在我的settings.py中添加“ DEFAULT_AUTHENTICATION_CLASSES”来解决

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




django-rest-framework