Three certified overall source code analysis, custom certification class, the class system permissions, custom permission class

"" " 
. 1) is APIView dispath (Self, Request, * args, ** kwargs) 
2) the method dispath self.initial (request, * args, ** kwargs) into the three authentication 
    # authentication component: verify the user - tourists, legitimate users of illegal users 
    # guests: representatives of the check is passed directly to the next check (check the permissions) 
    # legitimate users: check by representatives, will request.user, and then enter the next check user memory (check the permissions) 
    # unauthorized users: On behalf of the check fails, an exception is thrown, return 403 permissions abnormal results 
    self.perform_authentication (Request) 
    
    # privilege 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) 
    
    times the frequency limit view interface is accessed: # frequency components - condition (IP, id, a unique key) to limit the frequency cycle time (s, m, h), times (3 / s) frequency 
    # does not reach the time limit: normal access interface 
    # reaches time limit: Can not access the system time, time to reach the limit, can regain access 
    self.check_throttles (Request) 
    
    
. 3) Authentication Unit
    Request class get property methods of user => self._authenticate () completes the authentication 
    
    certification Details: 
    # do authentication 
    DEF _authenticate (Self): 
        # traversed to get one authenticator performs authentication 
        bunch configuration # self.authenticators authentication authentication class object class consisting generated List 
        for Authenticator in self.authenticators: 
            the try: 
                # Authorizer (object) calls the authentication method authenticate (certified class object self, request the requested object) 
                # return value: the user login information with authentication composed of tuple 
                # this method is try wrapped, on behalf of the method will throw an exception, throw an exception on behalf of authentication failure 
                user_auth_tuple = authenticator.authenticate (Self) 
            the except exceptions.APIException: 
                self._not_authenticated () 
                the raise 
 
            process # return value
            IF user_auth_tuple iS not None:
                = Authenticator self._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 
        # user_auth_tuple If the return value is null, certified by the representative, but no login authentication and login information, on behalf of tourists 
        self._not_authenticated () 

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

Custom certification categories:

"" " 
1) creates classes inherit authentication BaseAuthentication 
2) override authenticate method 
3) is determined in accordance with the authentication rule rewriting body tourists, illegal users, authorized users 
4) globally or locally configure 

authentication rules 
i. None No certification information is returned ( 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) 
"" "
utils/authentications.py
# Custom certification class 

# 1) inherits BaseAuthentication class 
# 2) rewrite authenticate (self, request) method, a custom authentication rule 
# 3) certification rules-based conditions: 
#        no authentication information return None (visitors) 
#        authentication information authentication failed Throws (illegal users) 
#        authentication information, authentication is successful, returns the user authentication information tuple (legitimate user) 
# 4) complete global 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:
            raise AuthenticationFailed('用户数据有误,非法用户')
        return (user, None)
 #全局配置:
   'DEFAULT_AUTHENTICATION_CLASSES': [
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
        'api.authentications.MyAuthentication',
    ]

Class system privileges

"" " 
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 
fromrest_framework.permissions Import IsAuthenticated
 class TestAuthenticatedAPIView (APIView): 
    permission_classes = [IsAuthenticated]
     DEF GET (Self, Request, * args, ** kwargs):
         return APIResponse (0, ' the Test login interface to access the ok ' ) 
    
 
# default global configuration: 
# because the default permission class global configuration is AllowAny 
# the settings.py 
REST_FRAMEWORK = {
     # permission class configuration 
    ' DEFAULT_PERMISSION_CLASSES ' : [
         ' rest_framework.permissions.AllowAny '  ,
    ],
}
    

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, without authority representatives, returns False 
"" "
# 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 ' )

 

Guess you like

Origin www.cnblogs.com/yangjiaoshou/p/11734044.html