Reader small image

You're reading from  Django in Production

Product typeBook
Published inApr 2024
Reading LevelIntermediate
PublisherPackt
ISBN-139781804610480
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Arghya Saha
Arghya Saha
author image
Arghya Saha

Arghya (argo) Saha, is a software developer with 8+ years of experience and has been working with Django since 2015. Apart from Django, he is proficient in JavaScript, ReactJS, Node.js, Postgres, AWS, and several other technologies. He has worked with multiple start-ups, such as Postman and HealthifyMe, among others, to build applications at scale. He currently works at Abnormal Security as a senior Site Reliability Engineer to explore his passion in the infrastructure domain. In his spare time, he writes tech blogs. He is also an adventurous person who has done multiple Himalayan treks and is an endurance athlete with multiple marathons and triathlons under his belt.
Read more about Arghya Saha

Right arrow

Mastering Django Authentication and Authorization

In Chapter 4, we learned how to use Django Admin to autogenerate a user interface (UI) for basic CRUD operations. While working with Django Admin, we used the default Django authentication and authorization systems. In this chapter, we will deep dive into the Django authentication system and learn how to use Django groups and permissions to implement authorization for resources. Django by default provides cookie-based session authentication, which works perfectly for browser-based applications, but when it comes to modern web apps, it is preferred to use token-based authentication. Django REST framework (DRF) provides token-based authentication out of the box, and we will learn how to integrate DRF token-based authorization into our project along with social login.

In this chapter, we will cover the following main topics:

  • Learning the basics of Django authentication
  • Customizing the User model
  • Using a OneToOneField...

Technical requirements

You should be familiar with the basic concepts of authentication and why authentication is required in web applications. We will be covering how to implement role-based access control (RBAC) in Django, so you are expected to have some basic understanding of the concepts of RBAC. You should also be familiar with the core concepts of OAuth 2.0 that Google and other social login providers use to provide authentication services to different apps.

Here is the GitHub repository that has all the code and instructions for this chapter: https://github.com/PacktPublishing/Django-in-Production/tree/main/Chapter05

Learning the basics of Django authentication

The first concern any user has while using an application in today’s world is, Is my data secure with the application? This is also the most important thing a developer should keep in mind – always develop a secure application. So, what does secure mean? Security can come into multiple levels, such as authentication, authorization, server security (that is, the server where the application is running is secure), and so on. In this chapter, we will focus on the most fundamental part of security, application authentication; that is, via a login. Django comes with a built-in authentication framework.

The batteries-included approach of Django provides an authentication system out of the box that gives us a basic user model that is plugged with session- (cookie)-based authentication. When we create a new Django project, by default, Django includes django.contrib.auth and django.contrib.sessions in the INSTALLED_APPS section of...

Customizing the User model

There are primarily two approaches via which we can customize the User model. Both of them have their equal advantages, so let us learn about them one by one:

  • Extending the User model by a one-to-one relation: Whenever there is a requirement to add additional fields to the user, this is one of the simplest and best solutions. In this approach, we would create a new model, say UserProfile, and then create a one-to-one relationship with the User model. Any new custom field would be added to the UserProfile model. I would recommend using this approach most of the time since this is one of the simplest and cleanest solutions that doesn’t need much effort from the developer’s end and serves our requirements.
  • Expand using AbstractUser and AbstractBaseUser model: This is another approach to expand the User model. In this approach, we would have to create our custom User model and inherit from the AbstractUser class or AbstractBaseUser class...

Using a OneToOneField relationship with the User model

One of the simplest ways to store custom user information in Django is by creating a new model and creating a OneToOneField relation with the default User model. Let us take a simple example to implement this approach.

We need to store the phone number and city for each user registering on our platform, but Django’s default User model does not have these fields present. We should create a new model to store this information for each user.

First, create a new custom Django app, custom_user. Then, add a new UserProfile model in the custom_user/models.py file:

from django.db import models
class UserProfile(models.Model):
    user = models.OneToOneField('auth.User', related_name='user_profile', on_delete=models.CASCADE)
    phone_no = models.CharField(unique=True, max_length=20)
    city = models.CharField(max_length=40)
   ...

Using Django permissions and groups

RBAC is a method of restricting access based on roles assigned to individual users. Django permissions and groups are some of the most thought-through and verbose RBAC systems I have come across in my career. One reason why I always choose Django for any tight-deadline project is primarily due to the authentication and authorization system it provides out of the box. In this section, we will get a high-level overview of how we can use Django groups and permissions in our project.

Using permissions and groups in Django Admin

In Chapter 4, while exploring Django Admin, we used a Django superuser to navigate through the admin panel; hence, there was no permission needed. But as our project moves to production, we want to give restricted access to each user depending upon their use case. For example, a support agent would need view-only access to all payment models and should not have access to any other database. These kinds of RBACs can easily...

Using DRF token-based authentication

Modern web applications are no longer limited to just browsers. In fact, more than 55% of internet traffic comes from mobile (as per this Cloudflare report: https://radar.cloudflare.com/traffic?range=28d). Django was first built more than 18 years ago when browsers were more prevalent, but in today’s world, there are more mobile devices and applications than browsers, which require a different type of authentication. DRF already provides multiple types of authentications out of the box:

  • Basic authentication
  • Session-based authentication
  • Token-based authentication
  • Remote user authentication

Token-based authentication is the most popular and widely used form of authentication in today’s world. In this section, we will learn how to enable and use token-based authentication in our Django project, the advantages of using token-based authentication, and another custom type of token-based authentication.

Integrating...

Learning about third-party token-based authentication packages

In this section, we will get a high-level overview of different packages available that can be plugged into Django and DRF to solve the challenges of DRF token-based authentication. We will not deep dive into the implementation and integration of the following package; rather, we will enable developers to know about the available open source packages out there that can be easily used by them to solve problems.

django-rest-knox

The django-rest-knox package provides multi-device login and session management support. It has a similar architecture to DRF token-based authentication, but it solves a couple of issues, such as saving tokens in an encrypted format and also providing expiry time for issued tokens.

Read more

For more details, check the official documentation at https://jazzband.github.io/django-rest-knox/.

djangorestframework-simplejwt

JSON Web Token (JWT) is a modern-age token-based authentication...

Integrating social login into Django and DRF

Social login is crucial for any client-facing application. In today’s modern world, users do not want to fill out lengthy forms to register, nor do they want to remember passwords for every site; these hurdles can be resolved using social login. There are multiple services, such as Google, Facebook, Twitter, and GitHub, that can be plugged into our website to enable social login. Each of these platforms has different implementation details, and it can be tricky to implement them. I recommend you use the python-social-auth third-party package to integrate social login into the Django application.

We will not get into the implementation details for python-social-auth (https://python-social-auth.readthedocs.io/en/latest/configuration/django.html) since there are multiple types of service providers available, such as Google, Facebook, GitHub, and so on. You are advised to go through the integration documentation for their respective...

Summary

In this chapter, we have learned how Django provides authentication out of the box. Django also provides authorization support with the help of Django permissions and groups. RBAC is one of the key security features that is needed by modern applications, which is provided out of the box by Django.

We have also learned how to use token-based authentication using DRF and Django. Token-based authentication is useful for non-browser clients, such as Android, iOS, and IoT devices. Social login is a must-have feature in today’s modern applications, and we have discussed how python-social-auth in Django can be used to integrate social login.

In the next chapter, we will learn more about how we can implement caching, logging, and throttling in Django applications and the added advantages they offer.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Django in Production
Published in: Apr 2024Publisher: PacktISBN-13: 9781804610480
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Arghya Saha

Arghya (argo) Saha, is a software developer with 8+ years of experience and has been working with Django since 2015. Apart from Django, he is proficient in JavaScript, ReactJS, Node.js, Postgres, AWS, and several other technologies. He has worked with multiple start-ups, such as Postman and HealthifyMe, among others, to build applications at scale. He currently works at Abnormal Security as a senior Site Reliability Engineer to explore his passion in the infrastructure domain. In his spare time, he writes tech blogs. He is also an adventurous person who has done multiple Himalayan treks and is an endurance athlete with multiple marathons and triathlons under his belt.
Read more about Arghya Saha