简体   繁体   中英

how to authenticate users in Django rest framework?

我在Django API中添加了一些用于发布删除和放置数据的URL,但我不知道如何首先对用户进行身份验证,以及如何使用其中的方法来禁止用户使用某些方法

As far as I know, you can use inbuilt decorator

@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

Since you are using the tag django-rest-framework, I assume that your view is being created with Django REST Framework.

First, you should force users to be authenticated to use the 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. Thus, you could create a custom permission to make sure that only a user that is a Django Super User will have permission:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM