This is the 21st day of my participation in the August More Text Challenge

Common built-in permissions

Different apis have different access rights. For example, ordinary users have the permission to read articles, but not to delete articles. So you need to use permissions to manage the API. The following are common DRF permissions:

  • Permissions.AllowAny: Allow all access. This permission is written with not written, generally not used.

  • Permissions. IsAuthenticated: login user can access. The check conditions are request.user and request.user.is_authenticated

  • Permissions.IsAdminUser: Administrators can access it. Request. user and request.user.is_staff

  • Permissions. IsAuthenticatedOrReadOnly: login user can access, or when the request is a read-only can access, is also the request for the GET, HEAD, or one of the OPTIONS.


Use the sample

views.py

from rest_framework import viewsets
from meituan.models import Merchant
from .serializers import MerchantSerializer
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from .authentications import generate_jwt, JWTAuthentication


class MerchantViewSet(viewsets.ModelViewSet) :
    queryset = Merchant.objects.all()
    serializer_class = MerchantSerializer

    # Specify the authentication mode to check whether the user has logged in successfully
    authentication_classes = [JWTAuthentication, BasicAuthentication]
    Restrict access based on user permissions
    permission_classes = [IsAuthenticated, IsAdminUser]


from django.contrib.auth import get_user_model
from rest_framework.response import Response
from rest_framework.decorators import api_view

User = get_user_model()


@api_view(['GET'])
def token_view(request) :
    Authentication is actually required to return the token
    # this is for demonstration only
    token = generate_jwt(User.objects.first())
    return Response({'token': token})
Copy the code

Specifying IsAuthenticated, IsAdminUser indicates that both are required to access the API.

Change is_staff to 0 in Navicat, send request, find failed.

Use ctrL-S to save your changes in Navicat.

Custom permissions

In DRF, in addition to using built-in permissions, you can also customize permissions.

There are two steps to customizing permissions:

  • Implements a class that inherits frompermissions.BasePermission.
  • implementationhas_permission(self, request, view)Or is ithas_object_permission(self, request, view, obj)Methods.

    The first method manages access to an entire view, while the second method can be used to manage access to an object (for example, modifying only its own user information).

    If both methods are defined, they must be passed firsthas_permissionTo gain access tohas_object_permissionThe authorization.

permissions.py

from rest_framework.permissions import BasePermission


class MyPermission(BasePermission) :
    def has_permission(self, request, view) :
        # Referer
        if request.META.get('HTTP_REFERER') :return True
        return False

    def has_object_permission(self, request, view, obj) :
        if 'the changsha' in obj.name:
            return True
        return False
Copy the code

views.py

from rest_framework import viewsets
from meituan.models import Merchant
from .serializers import MerchantSerializer
from rest_framework.authentication import BasicAuthentication
from .authentications import JWTAuthentication
from .permissions import MyPermission


class MerchantViewSet(viewsets.ModelViewSet) :
    queryset = Merchant.objects.all()
    serializer_class = MerchantSerializer

    # Specify the authentication mode to check whether the user has logged in successfully
    authentication_classes = [JWTAuthentication, BasicAuthentication]
    # permission control
    permission_classes = [MyPermission]
Copy the code

When using Postman, the Referer request header must be attached, otherwise the following error message will appear.

If the name of the visited business details does not contain the word ‘Changsha’, even if it carries the Referer, an error will be reported.