Hello everyone, here is my first blog in which I am going to give you a full guide on how you can manage user authentication and authorization in django. Well django is popularly known for how it makes things easier for us, so this tutorial is also going to be super easy for you guys.
User authentication in Django
Django comes with a user authentication system. It handles user accounts, groups, permissions and cookie-based user sessions. This section of the documentation explains how the default implementation works out of the box, as well as how to extend and customize it to suit your project’s needs.
Overview
The Django authentication system handles both authentication and authorization. Briefly, authentication verifies a user is who they claim to be, and authorization determines what an authenticated user is allowed to do. Here the term authentication is used to refer to both tasks.
Installation
Authentication support is bundled as a Django contrib module in django.contrib.auth. By default, the required configuration is already included in the settings.py generated by django-admin startproject, these consist of two items listed in your INSTALLED_APPS setting:
- ‘django.contrib.auth’ contains the core of the authentication framework, and its default models.
- ‘django.contrib.contenttypes’ is the Django content type system, which allows permissions to be associated with models you create.
Let’s begin our process
- To begin, first ensure django is installed in your system, if not follow the below command:-
$ pip install django
- Create our project directory. Also create an app inside our project directory:-
$ django-admin startproject myProject
$ cd ../myProject
$ python manage.py startapp UserAuth
- Migrate the database so we can get all our database tables:-
$ python manage.py migrate
- Do not forget to create a super user as a result , It will help in logging on the admin dashboard afterwords.:-
$ python manage.py createsuperuser
- Here we need to create a urls.py file under our app UserAuth to map our urls to the pages we want:-
from django.urls import path, include
from django.views.generic.base import TemplateView
urlpatterns = [
path('accounts/', include('django.contrib.auth.urls')),
path('', TemplateView.as_view(template_name = 'home.html'), name = 'home'
]
- Now we have to link the above urls.py file to urls.py file of our main project i.e. myProject. As a result when we will browse localhost we’ll get our app:-
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('UserAuth.urls'))
]
- Create a new directory inside the templates directory of your account application and name it registration. This is the default path where the Django authentication views expect your authentication templates to be.
$ mkdir templates/registration
- Create a new file inside the templates/registration directory, name it login.html, and add the following code to it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<p>Please login with your valid credentials</p>
<form action="" method="post" novalidate>
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Login">
</form>
<p><a href="{% url 'password_reset' %}">Reset Password</a> </p>
</body>
</html>
Here novalidate option is used because django uses the AuthenticationForm form located at django.contrib.auth.forms by default. This form tries to authenticate the user and raises a validation error if login was unsuccessful.
- Also we have already added our home.html url at the top. you need to create that file out side of the registration folder, just you need to add that file in the main templates, these are the files that we want to add in templates folder. basically home.html is for redirecting successful login.
Home.html:-
{% block body %}
{% if user.is_authenticated %}
Welcome {{user.username}}
<p><a href="{% url 'logout' %}">Logout</a> </p>
{% else %}
<p><a href="{% url 'login' %}" >Login</a></p>
{% endif %}
{% endblock %}
Base.html:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
basically we are going to authenticate if the use is valid.
- Edit the settings.py file of your project and add the following code to it:-
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
LOGIN_REDIRECT_URL: Tells Django which URL to redirect after a successful login if no next parameter is present in the request
LOGOUT_URL: The URL to redirect the user to log out So , here your User Authentication is done, Now we’re going to see social login.
Social Login in Django
We are going to implement social login using django. Here I have used ‘all-auth’ library using which we can login to the application by existing google or facebook accounts.
- Start by installing the django-allauth package in your project directory:-
$ pip install django-allauth
- Now go to the settings.py file and add the following things:-
INSTALLED_APPS =[
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook',
#local
‘UserAuth’,
]
- Now at the end of the file also add the site id:-
SITE_ID = 1
- Go to the urls.py file of your main project i.e. myProject include the following path:-
path('accounts/', include('allauth.urls')),
- Add the following template tags in login.html:-
TEMPLATE TAGS :
{% load socialaccount %}
{% providers_media_js %} (ONLY FOR FACEBOOK)
- Add the following hrefs to google and facebook login buttons in the login page:-
{% provider_login_url "facebook" method="js_sdk" %}
{% provider_login_url "facebook" method="oauth2" %}
{% provider_login_url "google" %}
- Now run the below command to make changes to the database:-
$python manage.py migrate
- Login to the admin panel. Go to socialapplication. Create an application out of the two providers google or facebook. But before that you need to have client id and secret key for the application which you can get by creating an app on the facebook developer site or google cloud platform. Given below are the links :-
GOOGLE DEVELOPER CONSOLE : https://console.developers.google.com/
FACEBOOK DEVELOPERS : https://developers.facebook.com
- Now go to Sites in admin panel and change the domain name:-
Domain name: localhost:8000/
Display name: localhost
- Run your django server and try logging in using your google and facebook accounts:-
$ python manage.py runserver
So here its done
So here its done Django social login !! Hope you guys learnt something from this.Thankyou!!
!! Hope you guys learnt something from this.Thankyou!!