【问题标题】:Django Rest Framework : Unable to create a protected resourceDjango Rest Framework:无法创建受保护的资源
【发布时间】:2015-11-11 11:22:21
【问题描述】:

我是 DRF 的新手,我想创建一个只能通过使用 Token Auth 标头访问的受保护资源。装饰器@authentication_classes 似乎不起作用。当我发送没有身份验证令牌标头的 GET 请求时 - $ curl http://127.0.0.1:8000/api/users/customers/2

我仍然得到响应 -

{"id":2,"person":{"id":2,"user":{"id":2,"mobile_number":"9999999999"},"first_name":"Yo","last_name":"Yolo","gender":"M"},"email":"b@b.com"}

我错过了什么?

settings.py

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

urls.py

from rest_framework.authtoken import views as rest_views
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^obtain-auth-token/', rest_views.obtain_auth_token),
    url(r'^customers/$', views.register_customer),
    url(r'^customers/(?P<pk>[0-9]+)$', views.customer_detail)
]

views.py

@api_view(["GET", "PUT"])
@authentication_classes([authentication.TokenAuthentication])
def customer_detail(request, pk):
    try:
        customer = Customer.objects.get(pk=pk)
    except Customer.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == "GET":
        serializer = CustomerSerializer(customer)
        return Response(serializer.data)

    elif request.method == "PUT":
        customer_serializer = CustomerSerializer(customer, data=request.data)
        person_serializer = PersonSerializer(customer.person, data=request.data)

        person_valid = person_serializer.is_valid()
        customer_valid = customer_serializer.is_valid()

        if person_valid and customer_valid:
            person_serializer.save()
            customer_serializer.save()
            return Response(request.data)
        else:
            errors = {}
            errors.update(person_serializer._errors)
            errors.update(customer_serializer._errors)

            return Response(errors, status=status.HTTP_400_BAD_REQUEST)

【问题讨论】:

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


    【解决方案1】:

    Django REST Framework 令牌认证只做认证,不做授权。您还需要设置权限。您可以在全球范围内进行:

    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
        )
    }
    

    或者作为装饰者:

    @api_view(["GET", "PUT"])
    @authentication_classes([authentication.TokenAuthentication])
    @permission_classes((IsAuthenticated,))
    def customer_detail(request, pk):
        pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 2015-10-01
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 2014-12-15
      相关资源
      最近更新 更多