In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the implementation method of django authentication class configuration". In daily operation, I believe many people have doubts about what is the implementation method of django authentication class configuration. Xiaobian consulted all kinds of materials and sorted out simple and easy operation methods. I hope to help you answer the doubts of "what is the implementation method of django authentication class configuration"! Next, please follow the small series to learn together!
I. Configuration authentication class
1. Authentication Global Profile
Certified source code flow analysis, DRF certification global configuration in api_settings, the following is api_settings part of the source code:
api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)def reload_api_settings(*args, **kwargs): setting = kwargs['setting'] if setting == 'REST_FRAMEWORK':#key of settings.py in project api_settings.reload()setting_changed.connect(reload_api_settings)
REST_FRAMEWORK in django, settings.py is referenced as key as configuration, so global configuration example:
#Global authentication configuration REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES":['API.utils.auth.Authentication',] #Write the path of the certified class, not in views, here I put it in auth.py under utils directory}2. Partial use
If authentication is not required for a local view, authentication_classes=[] is added to the view class.
authentication_classes = [] #authentication_classes is empty, which means authentication is not required. 3. Anonymous user configuration:
REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES":<$'API.utils.auth. Authentication',],#where the path to the authenticated class is written, not in views, here I put it in auth.py under utils directory "UNAUTHENTICATED_USER": lambda:"anonymous",#anonymous user configuration, only need the corresponding return value of the function or class, corresponding to request.user="anonymous""UNAUTHENTICATED_token": None,#anonymous token, only need the corresponding return value of the function or class, corresponding to request.auth=None} II, built-in authentication class
1.BaseAuthentication
BaseAuthentication is a django rest framework that provides us with the most basic authentication class. Just like the source code flow, two methods defined in this class authenticate and authenticate_header(response header returned after authentication failure) are rewritten when used for authentication, as shown in the example:
class BaseAuthentication(object): """ All authentication classes should extend BaseAuthentication. """def authenticate(self, request): """ Authenticate the request and return a two-tuple of (user, token). """raise NotImplementedError(".authenticate() must be overridden. ") def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """pass2. Other certification classes
##Path:rest_framework.authenticationBasicAuthentication #Browser-based authentication SessionAuthentication #django session-based authentication RemoteUserAuthentication #django admin user-based authentication, which is also an example of the official website TokenAuthentication #drf-based token authentication
1. Custom certification classes:
Inherit BaseAuthentication, override the authenticate method and authenticate_header(pass is OK), authenticate() method needs to have three cases (return to the ancestor, exception, return none).
2. Certification Configuration:
#global authentication REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES":<$'API.utils.auth. Authentication',]}#Partial authentication_classes = [BaseAuthentication,]#Is a view not authenticated authentication_classes =[]3. Source code flow:
1. In django(CBV), incoming requests from the client execute the view class's as_view method, while the as_view method executes the dispacth method, and then executes the corresponding methods (get, post, etc.) depending on the type of request (reflection).
2. View class in django rest framework needs to inherit APIView, request to reach view class will execute as_view method of view class, but OrderView does not have as_view() method, so execute as_view() method of APIView
3. From the APIView source code, you can see that as_view in APIView executes the as_view method of the parent class. Look at the parent class of APIView, which happens to be the view class in django.
4. From the View source code, we can see the execution flow of the as_view() method of the View class: verify the request method---> return the name of the view function (the view function will execute the dispatch method), once a request comes in, execute the view function--> execute the dispatch method.
5. After the as_view method of APIView executes the as_view method of the parent class, the incoming request will execute the view method, and the dispatch method will be executed in the view method, while Oderview has no dispatch method, so the dispatch method of the parent class (APIView) will be executed.
6. From APIView source code analysis, when executing APIView dispatch method, self.initialize_request method will be executed, which will encapsulate django original request.
7.self.initialize_request() source code analysis, instantiate the Request() class, encapsulate the original request,authenticators(authentication), execute self.get_authenticators(), here to start the django rest framework authentication process
8.self.get_authenticators() source code analysis, using list generation, loop self.authentication_classes, instantiate each of these classes, return the list, it is not difficult to find the authentication_classes attribute formally We use the authentication class list when authenticating, where we will automatically find the attribute for authentication. What if our view class does not define authentication methods? Of course, django rest framework has added default configuration to us. If we don't define it, we will automatically use DEFAULT_AUTHENTICATION_CLASSES in settings as default (global).
9. Continue to analyze APIView's dispatch method, execute the self. intrinsic method, and pass the encapsulated request object (Reuqest) as a parameter.
10. self.perform_authentication method is executed in the self. intrinsic method, while the self.perform_authentication method executes request.user. In this case, the request is the Request object, so the user attribute in the Request class needs to be analyzed.
11. From the source code analysis, in the Request object, the user attribute is an attribute method and will execute self._ authentication method,
12. From source code analysis, Request object self._ self.authenticators loop in authentication (the list is composed of authentication objects [object 1, object 2]), and execute the authenticate method in each object to return tuple, and at the same time catch exceptions in this process, any exceptions will be returned to the user, the following is the exception verification logic:
If there is an exception, execute self._ The not_authenticated() method continues throwing exceptions upward.
If any return value must be a tuple, assign it to self.user, self.auth(request.user and request.auth), respectively, and exit the loop.
If None is returned, the next loop will process it; if None is returned, self._ not_authenticated(), returns (Anonymous User,None)
13. When there is no return value, execute self._ not_authenticated(), equivalent to anonymous user, failed authentication, and at this time django will return the default anonymous user setting AnonymousUser, if you need to set the anonymous user return value separately, write the return value that needs to be written UNAUTHENTICATED_USER:
So after the above analysis, when we need to authenticate, we need to define authenticate in each authentication class for verification, and we need to return the ancestor.
At this point, the study of "what is the implementation method of django authentication class configuration" is over, hoping to solve everyone's doubts. Theory and practice can better match to help you learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.