day74_10_21 largest certification

One. Permissions six tables.

  Django general, the access control rights based on the user authentication is RBAC (Role-Based Access Control)

  There are some auth based authentication rules.

  Django framework uses RBAC certification rules, RBAC certification rules are usually divided into three meter rule, five meter rule, Django uses a six-meter rule.

  These tables need to inherit the class when the model is created: AbstractUser

  Three tables: a user table, table roles, permissions table.

  Five tables: a user table, table role, authority table, table user roles, role permissions table.

  Six tables: a user table, table role, authority table, user roles table, table role permissions, user permissions table.

  Between the user and role table are many-to-table,

  Between role permissions table is a table with many to many,

  Between the user and the permissions table is many-to-table.

  Used between the table and the table is as follows:

# User table: Role groups, permissions user_permi ssions 
# role table: User user_set, rights the Permissions 
# permissions table: user user_set, role group_set

  Note: If you create a table from the User-defined, another project to create a native User complete database migration, they might fail, can have the following solutions: 

  1) Uninstall Django reinstall.

  2) The following django.contrib admin, database migration log files in the auth empty.

two. Analysis of the three certified source.

  From APIview first you need to distribute tasks in a dispatch:

    dispath(self, request, *args, **kwargs)

  Three certification from re-entering the initial dispatch

self.initial (Request, * args, ** kwargs) # to enter the three certification

  Three certification are the following certification:

  1. User verification:

    # Authentication component: check users - tourists, legitimate users of illegal users 
    # guests: representatives of the check is passed directly to the next check (check the permissions) 
    # legitimate users: on behalf of verification by the user is stored in request.user , and then enter the next check (check the permissions) 
    # unauthorized users: On behalf of the check fails, an exception is thrown, return 403 permissions abnormal results 
    self.perform_authentication (request)

  2. Check permissions.

    # Permissions components: check user rights - must log all user, login to read and write read-only visitors, custom user roles 
    # authentication: You can enter the next check (frequency certification) 
    # authentication failure: an exception is thrown, return 403 permissions abnormal results 
    self.check_permissions (request)

  3. Frequency check.

    # Frequency components: limiting the number of frequency view of the interface to be accessed - Condition (IP, id, a unique key) limit, 
      clock cycle time (s, m, h), times (3 / s) frequency
# does not reach the threshold times: normal access interface # achieve limited time: can not be accessed within the time limit, the time limit reaches, you can revisit self.check_throttles (request)

three. User Authentication

  In the process of user authentication, it is necessary to note that request.user get method is to obtain user, as well as self represents the request.

    # Do certification 
    DEF _authenticate (Self):
         # traversing get one authenticator, authentication 
        # certification class object pile certification class self.authenticators configured to generate a composition List 
        for Authenticator in self.authenticators:
             the try :
                 # authenticator (Object) call authentication method the authenticate 
            (certification class object self, request the requested object)
# return value: tuple information of the user and the authentication landing composition # this method is try wrapped, on behalf of the method will throw an exception, throw an exception on behalf of certification failed user_auth_tuple = authenticator.authenticate (Self) the except exceptions.APIException: self._not_authenticated () the raise # return value processing ifuser_auth_tuple IS not None: self._authenticator = Authenticator # How to return a value, it will login and login authentication are
            saved to request.user, request.auth
self.user, self.auth = user_auth_tuple return # If the return value is null user_auth_tuple representatives of certification through, but there is no user login and
          login authentication information, on behalf of tourists
self._not_authenticated ()

four. Custom certification class.

  When custom authentication class, can require the following steps:

"" " 
1) Create succession BaseAuthentication authentication class 
2) implemented authenticate method 
3) implementation thereof is determined visitors accordance with the authentication rule, illegal users, authorized users 
4) globally or locally configure 

authentication rules 
i. No certification information is returned None (tourists) 
ii. there authentication information fails throwing an exception (illegal users) 
iii. has successfully returned to the user authentication information and authentication information tuple (legitimate user) 
"" "

  Custom follows:

# Custom certification class 

# 1) inherits BaseAuthentication class 
# 2) to re-authenticate (self, request) method, a custom authentication rule 
# 3) certification rules-based conditions: 
#        no authentication information return None (visitors) 
#        there is authentication information failure to throw an exception (illegal users) 
#        has successfully returned to the user authentication information and authentication information tuple (legitimate user) 
# global 4) full view class (settings file) or partial (exact view class) configuration 
from rest_framework.authentication Import BaseAuthentication
 from rest_framework.exceptions Import AuthenticationFailed
 from . Import Models
 class MyAuthentication (BaseAuthentication):
     "" "
    With the front desk to get authentication information request header auth (authentication field to get the reception in the agreement) 
    no auth tourists, return None 
    have auth checksum 
        failure is an illegal user, an exception is thrown 
        success is a legitimate user, return (user authentication information) 
    "" " 
    DEF the authenticate (Self, request):
         # reception authentication information carried in the request header, 
        #        and carries the authentication information with the default specification Authorization field 
        #        background field of the request META fixed object HTTP_AUTHORIZATION obtain 
        auth = request.META.get ( ' HTTP_AUTHORIZATION ' , None) 

        # processing tourists 
        IF auth IS None:
             return None 

        # set about the small field certification rule (two-stage): "auth authentication string" 
        auth_list = auth.split () 

        #Check lawful or unlawful user 
        IF  not (len (auth_list) == 2 and auth_list [0] .lower () == ' auth ' ):
             The raise AuthenticationFailed ( ' authentication information is incorrect, illegal user ' ) 

        # legitimate user also need to parse the auth_list [1] out 
        # Note: a case is assumed, information abc.123.xyz, admin users can be parsed; actual development, the logic must check logic is a normal user 
        IF auth_list [1] ! = ' abc.123.xyz ' :   # check fails 
            The raise AuthenticationFailed ( ' user verification fails, the illegal user ' ) 

        user = models.User.objects.filter (username = ' ADMIN' ) .First () 

        IF  Not User:
             The raise AuthenticationFailed ( ' User data error, illegal users ' )
         return (User, None)
utils/authentications.py

 

Fives. Certification authority.

  Certification authority must be authenticated by the user, and wherein the user must have a value.

4 ) rights component 
    self.check_permissions (request) 
    Certification Rules: 
    DEF check_permissions (Self, Request):
         # traverse permissions for a list of objects to get a permission object (an authority), a certification authority 
        for permission in self.get_permissions ():
             # Permissions there must be a class method has_permission authority, certification authority used to make 
            # parameters: the rights object self, request object request, view class object 
            # return value: returns True have permission, no authority returns False 
            IF  not permission.has_permission (request, Self ): 
                self.permission_denied ( 
                    Request, Message = getattr (permission, ' Message ' , None) 
                )

  Permission class system, there is provided a method of identifying the following permissions, these methods can be configured in a locally defined method of class:

"" " 
1) AllowAny: 
    certification rules all returned True: return True 
        tourists and landing users have all permissions 

2) IsAuthenticated: 
    certification rules must have a valid user login: 
    return BOOL (request.user and request.user.is_authenticated) Guest no permissions, users have landing rights 3) IsAdminUser: certification rules must be Admin user:
    return BOOL (request.user and request.user.is_staff) visitors do not have any rights, privileges users have landed 4) IsAuthenticatedOrReadOnly certification rules must is read-only requests or legitimate users: return BOOL ( request.method in SAFE_METHODS or request.user and request.user.is_authenticated ) visitors read only legitimate users unlimited
"" " # API / views.py from rest_framework.permissions Import IsAuthenticated class TestAuthenticatedAPIView (APIView): permission_classes = [IsAuthenticated] DEF GET (Self, Request, * args, ** kwargs): return APIResponse (0, ' the Test log in to access the interface ok ' ) # because the default global permission class is AllowAny # the settings.py REST_FRAMEWORK = { # permission class configuration ' DEFAULT_PERMISSION_CLASSES ' : [ ' rest_framework.permissions.AllowAny ' , ], }

six. Custom permission class.

  Need to follow these methods in a custom permission class:

"" " 
1) Create BasePermission inherited permission class 
2) has_permission implemented method 
3) implemented to determine whether the body according to the permission rights rules 
4) globally or locally configure 

authentication rules 
i. The user setting condition is satisfied, representing authority, return True 
ii. does not meet the conditions set by the user, representing authority, return False 
"" "

  Custom follows:

# Utils / permissions.py 
from rest_framework.permissions Import the BasePermission
 from django.contrib.auth.models Import Group
 class MyPermission (the BasePermission):
     DEF has_permission (Self, Request, View):
         # Read-Only Interface Analyzing 
        R1 = request.method in ( ' the GET ' , ' the HEAD ' , ' the OPTIONS ' )
         # Group as a privileged packet 
        Group Group.objects.filter = (name = ' administrators ' ) .first ()
        # All packets groups belong to the current user 
        groups = request.user.groups.all () 
        r2 = Group and groups 
        r3 = Group in groups
         # read the interface we have permission to write the user interface must be landed in designated groups 
        return r1 or (r2 and r3) 
    
    
# tourists read-only, read-only user login, only the logged-on user belongs to the administrators group can only be additions and deletions 
from utils.permissions Import MyPermission
 class TestAdminOrReadOnlyAPIView (APIView): 
    permission_classes = [MyPermission]
     # All users can access 
    DEF GET (Self, Request, * args, **kwargs):
         return APIResponse (0, ' custom reading the OK ' )
     # must be custom "Admin" user packet under 
    DEF POST (Self, Request, * args, ** kwargs):
         return APIResponse (0, ' from write the definition of the OK ' )
utils/permissions.py

 

 

 

 

 

 

 

 

 

 

Role-Based Access Control

Guess you like

Origin www.cnblogs.com/LZXlzmmddtm/p/11717253.html