How to add authentication to Django Website?


In a web application, there are two key elements to data management. The first is to save data acquired from multiple browser queries, and the second is to use this preserved data to authenticate users. Sessions allow us to keep track of data across numerous browser queries. The second half of the equation is logging in users using those sessions.

We cannot trust people to be who they claim they are, so we have to verify their identities along the process. Django, of course, includes tools to perform these and other typical tasks. User accounts, groups, permissions, and cookie-based user sessions are all managed by Django's user authentication system. An auth/auth (authentication and authorization) system is a term used to describe this system.

The name (auth/auth) recognizes that dealing with users is often a two-step process.

  • Check a username and password against a database of users to verify (authenticate) that a person is who he or she claims to be.

  • Verify (authorize) that the user is authorized to do a specific operation, usually by comparing the user's permissions to a table.

There are many parts to the Django’s auth/auth system. All of these parts are seen below.

  • Users − Your users are people who have signed up for your website.

  • Permissions − These are binary (yes/no) markers that indicate whether or not a user is allowed to do a specific task.

  • Groups − A mechanism to apply labels and permissions to several users in a general way.

  • Messages − A simple way for users to queue and see system messages.

  • Profiles − A way for adding custom fields to the user object.

Django authentication combines authentication and authorization into a single package, which is referred to as the authentication system because these functions are somewhat intertwined.

Authentication support is included in django.contrib as a Django application that must be installed. It is installed by default, but if you have uninstalled it, you'll need to reinstall it using the procedures below.

Verify that the session framework is in place. Keeping track of users, of course, requires the usage of cookies, which is why the session framework is used.

  • Run manage.py syncdb after adding 'django.contrib.auth' to your INSTALLED APPS configuration.

  • After SessionMiddleware, make sure 'django.contrib.auth.middleware.AuthenticationMiddleware' is in your MIDDLEWARE CLASSES settings.

Authenticating Users

django.contrib.auth is a Django contrib module that provides authentication capabilities.

The necessary setup is included by default in the settings.py file generated by django-admin startproject.

  • These are the following two things in your INSTALLED APPS setting −

  • The authentication framework's core and default models are found in 'django.contrib.auth.'

  • The Django content type system, which allows you to associate permissions with models you develop, is called 'django.contrib.contenttypes.'

and the following items in your MIDDLEWARE configuration −

  • SessionMiddleware is a middleware that manages sessions across requests.

  • AuthenticationMiddleware uses sessions to link users to requests.

Running the command manage.py migrate with these settings in place provides the appropriate database tables for auth related models and permissions for any models configured in your installed apps.

Authenticate() method

We can use the authenticate() method to verify a set of credentials. It takes username and password and checks them against each for authentication. It returns a user object if the credentials provided are valid for a backend. If not, a PermissionDenied error is raised, and None is returned.

from django.contrib.auth import authenticate
user=authenticate(username=’john’,password=’passwordjohn’)
if user is not None:
   #backend has authenticated the given data
else:
   #no backend has authenticated the given data

The above provided method is a low-level authentication method.

An example of user entered data authentication during login can be seen below.

def login(request):
   if request.method == 'POST':
      name = request.POST['name']
      password = request.POST['password']

      user = auth.authenticate(username=name,password=password)
      if user is not None:
         auth.login(request,user)
         messages.info(request,'You Have Successfully LogedIn')
         return redirect('/')
      else:
         messages.info(request,'Invalid Details')
         return redirect('login')
   else:
      return render(request, 'login.html')

In this way, authentication can be performed on user entered data.

Updated on: 05-Sep-2022

523 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements