drf-Authentication Certification
# # Source code analysis `` `Python " "" 1) APIView of dispath (self, request, * args , ** kwargs) within 2) dispath method self.initial (request, * args, ** kwargs) into the largest certification # 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) # privilege components: check user permissions - must sign in, all users log in 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) # frequency components: limit the number of frequencies to be accessed view of the interface - the 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 visits Interface # reached the limit time: Can not access the restricted hours, the time limit is reached can revisit self.check_throttles (Request) . 3) Authentication Unit Method Request class of user attribute get method => self._authenticate () completes the authentication certification Details: # do authentication DEF _authenticate (Self): # traversed to get one authenticator, authenticating the authentication certification class object class # self.authenticators pile is configured to generate a composition 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: tuple information and user authentication landing composition # 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 # Returns the value of the deal # parameters: the rights object self, request object request, view class object None not user_auth_tuple IS IF: 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 user_auth_tuple empty, on behalf of authenticated, but not logged in user login and authentication 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 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 # return value: have permission to return True, no authority returns False Not permission.has_permission IF (Request, Self): self.permission_denied ( Request, Message = getattr (permission, 'Message', None) ) "" " ` `` # ### custom authentication class `` `Python " " " 1) Create succession BaseAuthentication authentication class 2) implemented authenticate method 3) implementation thereof is determined in accordance with the authentication rule tourists, 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) "" " ` `` # #### utils / authentications.py `` `Python # custom certification class # 1) inherits BaseAuthentication class #2) re-authenticate (self, request) method, a custom authentication rule # 3) certification rules-based conditions: # no authentication information return None (visitors) # authentication information authentication fails throwing an exception (illegal users) # there is authentication information successfully returned to 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 has 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): # foreground carrying authentication information in the request header, # and the default specification for Authorization field carries authentication information, # background fixed in the request object META field HTTP_AUTHORIZATION get 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 () == ' the auth ' ): The raise AuthenticationFailed ( ' authentication information is incorrect, the illegal user ' ) # legitimate user needs to resolve from auth_list [1] in # 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 is wrong, illegal user ' ) return (the User, None) `` ` ` `` Python # Homework # 1) ordinary users can create three scripts based auth components using: models.User.objects.create_user ( ) # Note: direct write register interface better # 2) custom session table: id, u_id, token, a fixed personal authentication string configuration for each user can directly manipulate the database # Note: register interface implemented in a more good # 3) custom certification classes, different token can check out different login `` ` # ### system privileges like ` `` Python "" " 1) AllowAny: certification rules all returned True: return True visitors 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) Visitors do not have any rights, privileges users have landed 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 be read-only request 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 = [the IsAuthenticated] DEF GET (Self, Request, args *, **kwargs): return APIResponse (0, ' the Test login interface to access the ok ' ) # because the default permissions class global configuration is AllowAny # settings.py REST_FRAMEWORK = { # permission class configuration ' DEFAULT_PERMISSION_CLASSES ' : [ ' rest_framework.permissions.AllowAny ' , ], } `` ` # ### custom permission class ` Python "" " . 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) global or local configuration authentication rules i. satisfies the conditions set by the user, authority representatives, return True ii. does not satisfy the conditions set by the user, authority representatives, returns False "" " ` `` `` `Python # 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 = GET (Self, Request, * args, **[MyPermission] # All users can access DEFkwargs): 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 ' ) `` `