Django REST framework security practice: easily implement authentication, permissions and current limiting functions

A directory of articles in the series

  • Getting Started with Django: Building Your First Web Project from Scratch
  • Getting Started with Django ORM: From concept to practice, master model creation, migration, and view manipulation
  • Django ORM Practice: Model Field and Meta Option Configuration, as well as Chain Filtering and QF Query
  • Django ORM Deep Tour: Exploring the Mystery and Practice of Many-to-One, One-to-One and Many-to-Many Data Relationships
  • Cross-domain issues and Django solutions: In-depth analysis of cross-domain principles, request handling, and CSRF protection
  • Django View Layer Exploration: GET/POST Request Processing, Parameter Passing, and Response Modes
  • Django Routing and Session Deep Dive: Static and Dynamic Routing Distribution, and the Mystery of Cookies and Sessions
  • Django API Development Practice: Separation of Front and Back End, Restful Style and DRF Serializer
  • Django REST framework Serializer: Selection and Application of Common Serializer and Model Serializer
  • Django REST framework association serializer details: master the art of serialization and deserialization of complex relationships
  • GenericAPIView in Django REST framework and Detailed Explanation of Mixed Extension Class
  • Django REST framework View Set and Routing in Detail: In-depth Understanding of ViewSet, ModelViewSet, and Route Mapper
  • Django Middleware Exploration: Revealing the Daemon Role and Practical Application of Middleware in Web Applications
  • Django REST framework Data Presentation Skills: Practical Configuration and Practice of Paging, Filtering and Searching
  • Django REST framework Security Practices: Easily Implement Authentication, Permissions, and Limiting
  • Study hard 0.0ing …

Article Directory

  • A directory of articles in the series
  • Foreword
  • I. Certification
  • II. Authority
  • III. Current Limiting
    • 1. Anonymous user global current limiting
    • 2. Anonymous user local current limiting
  • IV. Global Configuration Example of Authentication, Permission and Current Limiting

Foreword

    in the text,we will delve into_Django REST frameworkThe three core components in:Certification、Permissions and current limiting_。first,We'll reveal how certification protectsAPIaccess permission、Key role in verifying user identity,and introduce how toDjango REST frameworkConfiguring and using different authentication schemes in。then,We will discuss permission control,Learn how to restrict access by different users toAPIResource access,Keep sensitive data safe。at last,We will discuss current limiting techniques,Learn how to preventAPIabused,Ensure service stability and availability。


I. Certification

_Django comes with a user authentication system. It handles user accounts, groups, permissions, and cookie-based user sessions. _
The Django authentication system handles authentication and authorization. Simply put, Validate verify that the user is their user and Authorization decide what the authenticated user can do.

_The certification system consists of the following components: _

  • User
  • Permissions: Binary (Yes/No) identifies whether a specified user can perform a specific task.
  • Group: a general way to apply labels and permissions to multiple users.
  • Configurable password hashing system
  • Provides form and view tools for logged in users or restricted content
  • Pluggable back-end system

_The authentication system in Django is intended to be generic and does not provide the features of some common web authentication systems. _。 Solutions to some of these common problems have been implemented in third-party packages.

  • Password strength check
  • Restrict login attempts
  • Authentication to third parties (e.g. OAuth)
  • Object-level permissions

You can configure the global default authentication scheme in the configuration file. Authentication needs to be used together with permission.

#settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':(

        #basic authentication
       'rest_framework.authentication.BasicAuthentication',
        # sessionCertification
       'rest_framework.authentication.SessionAuthentication', 
    ),
) 

_Authentication failure has two possible return values: _

  • 401 Unauthorized
  • 403 Permission Denied permission is prohibited

II. Authority

_ Permission control _ You can restrict user access to views and access to specific data objects.

Before the method of the dispatch() view is executed Judgment of view access permission. When a specific object is obtained through get_object(), Judgment of object access permission the

_You can set the default permission management class in the configuration file, such as: _

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

_If not specified, the default configuration is as follows: _

REST_FRAMEWORK = {
'DEFAULT PERMISSION CLASSES' : (
    'rest _framework.permissions.ALLowAny'
    )
} 

_Permissions provided: _

  • AllowAny Allow all users
  • Authenticated users IsAuthenticated only
  • Administrator users IsAdminUser only
  • IsAuthenticatedOrReadOnly Authenticated users can fully operate, otherwise they can only get read

III. Current Limiting

Is similar Current-limiting to Permissions because it determines whether the request should be authorized. _ flow limiting valve _ indicates a temporary state and is used to control the rate at which clients can make requests to the API.

1. Anonymous user global current limiting

The frequency of interface access can be limited to reduce the pressure on the server. In particular, the crawling of the crawler is limited.

_ ** In the configuration file, use DEFAULT_THROTTLE_CLASSES and DEFAULT_THROTTLE_RATES for global configuration: ** _

 REST_FRAMEWORK = {
      'DEFAULT_THROTTLE_CLASSES': (
          # Restrict all anonymous unauthenticated users,useIPDistinguish between users
          'rest_framework.throttling.AnonRateThrottle',
          #Current limit for authenticated users
          'rest_framework.throttling.UserRateThrottle',
      ),
      'DEFAULT_THROTTLE_RATES': {
          # can use second, minute, hour ordayto indicate the cycle
          'anon': '3/minute',
          'user': '5/minute'
      }
  } 

2. Anonymous user local current limiting

_ ** Use throttle_classes attributes to set the type ** of throttling user in the view _

 from rest_framework.generics import ListAPIView
  from serializer import UserSerializer, User

  from rest_framework.throttling import AnonRateThrottle



  class UserView(ListAPIView):
      queryset = User.objects.all()
      serializer_class = UserSerializer
      throttle_classes = [AnonRateThrottle]  
      # Indicates flow restriction for anonymous users,Current limiting frequency global configuration 

_Set the specific frequency for the user type in the project profile: _

 REST_FRAMEWORK = {
      'DEFAULT_THROTTLE_RATES': {
          # can use second, minute, hour ordayto indicate the cycle
          'anon': '3/minute',
          'user': '5/minute'
      }
  } 

IV. Global Configuration Example of Authentication, Permission and Current Limiting

# settings.py
# Certification,Permissions,Limiting
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES':(
        #basic authentication
        'rest_framework.authentication.BasicAuthentication',

        # sessionCertification
        'rest_framework.authentication.SessionAuthentication', 
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_THROTTLE_CLASSES': (
          # Restrict all anonymous unauthenticated users,useIPDistinguish between users
          'rest_framework.throttling.AnonRateThrottle',
          #Current limit for authenticated users
          'rest_framework.throttling.UserRateThrottle',
    ),
    'DEFAULT_THROTTLE_RATES': {
          # can use second, minute, hour ordayto indicate the cycle
          'anon': '3/minute',
          'user': '5/minute'
    }

}