[英]how to authenticate users in Django rest framework?
我在Django API中添加了一些用于发布删除和放置数据的URL,但我不知道如何首先对用户进行身份验证,以及如何使用其中的方法来禁止用户使用某些方法
As far as I know, you can use inbuilt decorator 据我所知,您可以使用内置装饰器
@user_passes_test @user_passes_test
then you can specify who can access your views just like below, 然后您可以指定哪些人可以访问您的视图,如下所示,
from django.contrib.auth.decorators import user_passes_test
def admin_user(user):
return user.is_superuser # write your logic here
@user_passes_test(admin_user)
def your_view(request):
--------
Have a look at the documentation for more clarification: https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.decorators.user_passes_test 请查看文档以获取更多说明: https : //docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.decorators.user_passes_test
Since you are using the tag django-rest-framework, I assume that your view is being created with Django REST Framework. 由于您使用的是django-rest-framework标签,因此我假设您的视图是使用Django REST Framework创建的。
First, you should force users to be authenticated to use the API . 首先,您应强制对用户进行身份验证以使用API 。 Second, you need to define what types of permissions are needed to perform the actions. 其次,您需要定义执行操作所需的权限类型 。
You stated that Django Super Users should be able to perform these actions. 您声明Django超级用户应该能够执行这些操作。 Thus, you could create a custom permission to make sure that only a user that is a Django Super User will have permission: 因此,您可以创建一个自定义权限,以确保只有作为Django超级用户的用户才具有该权限:
from rest_framework.permissions import BasePermission
class IsSuperUser(BasePermission):
"""
Allows access only to admin users.
"""
def has_permission(self, request, view):
is_superuser = request.user and request.user.is_superuser
if not is_superuser and request.user:
# Your ban logic goes here
pass
return is_superuser
Then on your view, you can do: 然后,根据您的看法,您可以执行以下操作:
from rest_framework.views import APIView
from your_app.permissions import IsSuperUser
class YourApiView(APIView):
permission_classes = [IsSuperUser]
If this is not enough information for you, I would suggest that you follow Django REST Framework's tutorial . 如果这还不足以为您提供信息,我建议您遵循Django REST Framework的教程 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.