Understanding authentication and permissions in Django, the Django REST framework, and RESTful Web Services

Right now, our sample RESTful Web Service processes all the incoming requests without requiring any kind of authentication, that is, any user can perform requests. The Django REST framework allows us to easily use diverse authentication schemes to identify a user that originated the request or a token that signed the request. Then, we can use these credentials to apply permission and throttling policies that will determine whether the request must be permitted or not.

We already know how configurations work with the Django REST framework. We can apply a global setting and override it if necessary in the appropriate class-based views. Hence, we can set the default authentication schemes in the global settings and override them whenever required for specific scenarios.

The settings allow us to declare a list of classes that specify the authentication schemes to be used for all the incoming HTTP requests. The Django REST framework will use all the specified classes in the list to authenticate a request, before running the appropriate method for the class-based view based on the request.

We can specify just one class. However, it is very important to understand the behavior in case we have to use more than one class. The first class in the list that generates a successful authentication will be responsible for setting the values for the following two attributes for the request object:

  • user: This attribute represents the user model instance. In our examples, we will work with an instance of the Django User class, specifically, the django.contrib.auth.User class.
  • auth: This attribute provides additional authentication data required by the authentication scheme, such as an authentication token.

After a successful authentication, we will be able to use the request.user attribute within the different methods in our class-based views that receive the request parameter. This way, we will be able to retrieve additional information about the user that generated the request.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.61.142