Introduction

We’re pleased to discuss a new aspect of social authentication in Django: adding Facebook authentication to your apps. We’re increasing the number of authentication methods available to customers to give them even more seamless sign-in experiences. This comes after we successfully implemented Google authentication using Django-Allauth and improved user engagement.

Social login features like Facebook authentication offer users convenient ways to access your web application without the hassle of managing additional credentials. In this post, we’ll guide you through setting up Facebook authentication with Django-Allauth. We’ll cover essential configurations, customization techniques, data management practices, testing strategies, and critical security considerations to ensure a seamless and secure integration.

If you’ve found value in our previous discussion on Google authentication, you’ll appreciate the insights and techniques shared in this guide for integrating Facebook authentication. Let’s continue our journey of empowering Django applications with versatile social authentication capabilities, focusing this time on seamlessly incorporating Facebook authentication into your project!

Check out our comprehensive guide on Django + Google Authentication: Elevate Your App’s Security With This Comprehensive Guide.

Step 1: Setting Up Project Workflow

Initially, set up a new virtual environment, followed by creating a Django project and a Django App within it.

1.1 Create a virtual environment.

python3 -m venv env_social_login

1.2 Active virtual environment in Linux.

source env_social_login/bin/activate

1.3 To activate a virtual environment in Windows, run the below command.

env_social_login\Script\activate

1.4 Install Django within your virtual environment to encapsulate its dependencies and version, ensuring compatibility with your project.

pip install django

1.5 Create a new Django project using the following command.

django-admin startproject social_login
cd social_login/

1.6 Create a new App using the following command.

python manage.py startapp authapp

Step 2: Installing Requirements

Install the all-auth package within your Django project’s virtual environment, and configure its settings as necessary to meet requirements.

2.1 Install the all-auth package within your virtual environment by executing the following installation command.

pip install django-allauth
pip install django-allauth[socialaccount]

2.2 Configure the settings for all-auth according to your project’s requirements, ensuring proper integration and functionality within your Django application.

  • Include the following configuration settings within the settings.py file of your social_login project:
import os


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.request',
            ],
        },
    },
]


AUTHENTICATION_BACKENDS = [
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by email
    'allauth.account.auth_backends.AuthenticationBackend',
   
]
  • Add the following entry to the INSTALLED_APPS list within the settings.py file of your project:
'authapp',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',  # for facebook login
  • Add the following middleware configuration to the MIDDLEWARE list within the settings.py file of your project:
'allauth.account.middleware.AccountMiddleware',
  • Add the following code snippet to the urls.py file of your project:
from django.urls import path, include
path('accounts/', include('allauth.urls')),
  • Execute the following command to generate your database tables, create a superuser account, and gain access to the admin panel:
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

Now you can access the admin panel using the below link.

http://127.0.0.1:8000/admin

Step 3: Create a Facebook App

  • If you don’t have a Facebook Developer account, create one. 
  • To Authcated users using Facebook accounts, we’ll need a Facebook app. For that, go to https://developers.facebook.com/apps/ and click on “Create App”.

Select the “Other” option for your app and click on the “Next” button.

Select the “consumer” option for your app and click on the “Next” button.

Provide “Add an app name” and “App Contact Email”, and hit the “Create App” button. You’ll have to go through a security check to create an app.

Select “Set Up” of “Facebook Login” Product.

Then, Go to the “App settings” and select “Basic”.

Add the below requirement in the open from:

Now store the App ID and App Secret and click on “Save Changes”.

If you want to enable authenticated user login via Facebook on your website or server, follow these steps:

  1. Configure Facebook App Settings:
  • Add your domain name to the ‘App Domains’ field.
  • Provide the Privacy Policy URL for your website.
  • Add the Site URL of your website.
  1. Business Verification:
  • Click on “Start Verification” to verify your business.
  1. Facebook Login Product Settings:
  • Save your changes.
  • Go to the Facebook Login Product settings.
  1. OAuth Redirect URL:
  • Add the following URL to the ‘Valid OAuth Redirect URLs’:
  • https://<Domain_name>/accounts/facebook/login/callback/
  1. App Review:
  • Navigate to the App Review section.
  • Click on ‘Permissions and Features’.
  1. Request Access:
  • Click the ‘Request’ button for standard access to ‘public_profile’ and ’email’.
  1. App Mode Toggle:
  • Toggle the App mode from Development to Live.

Step 4: Configuring Client ID and Client Secret in Django

4.1 Include the following configuration in your settings.py file:

SOCIALACCOUNT_PROVIDERS = {
    
   'facebook': {
        'APP': {
            'client_id':<your_app_id>,
            'secret': <your_app_secret>
        },
        'METHOD': 'oauth2',  # Set to 'js_sdk' to use the Facebook connect SDK
        'SDK_URL': '//connect.facebook.net/{locale}/sdk.js',
        'SCOPE': ['email', 'public_profile'],
        'AUTH_PARAMS': {'auth_type': 'reauthenticate'},
        'INIT_PARAMS': {'cookie': True},
        'FIELDS': [
            'id',
            'first_name',
            'last_name',
            'middle_name',
            'name',
            'name_format',
            'picture',
            'short_name',
        ],
        'EXCHANGE_TOKEN': True,
        'VERIFIED_EMAIL': False,
        'VERSION': 'v17.0',
        'GRAPH_API_URL': 'https://graph.facebook.com/v17.0',
    }

}


LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
LOGIN_REDIRECT_URL = 'dashboard'
LOGOUT_REDIRECT_URL = 'login'

SOCIALACCOUNT_AUTO_SIGNUP = True
SOCIALACCOUNT_LOGIN_ON_GET = True

4.2 Add the following code snippet to the views.py file of your Django app:

from django.shortcuts import render, redirect
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout

# Create your views here.
def userLogin(request):
    return render(request,'login.html')

@login_required
def dashboard(request):
    print(request)
    return render(request,'dashboard.html')

def userlogout(request):
    # Logout the user
    logout(request)
    return redirect('login')

4.3 Create a urls.py file in your authapp and add the following code:

from django.urls import path
from .views import userLogin, dashboard, userlogout

urlpatterns = [
    path('', userLogin, name='login'),
    path('dashboard/', dashboard, name='dashboard'),
    path('logout/', userlogout, name='logout'),
]

4.4 Add the following code snippet to the urls.py file of your project:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('authapp.urls')),
    path('accounts/', include('allauth.urls')),
]

4.5 Create a “templates” folder at the project level of your Django project, and then add the login.html and dashboard.html templates into this folder.

login.html

{% load socialaccount %}
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>

</head>
<body>

    <div class="container mt-5">
        <div class="row justify-content-center login-container">
          <div class="col-md-6 col-sm-8 col-lg-4">
            <div class="card">
              <div class="card-header">
                Login
              </div>
              <div class="card-body">
                <form>
                  <div class="form-group">
                    <label for="username">Username</label>
                    <input type="text" class="form-control" id="username" placeholder="Enter username">
                  </div>
                  <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" class="form-control" id="password" placeholder="Enter password">
                  </div>
                  <button type="submit" class="mt-2 btn btn-primary btn-block">Login</button>
                  <a href="{% provider_login_url 'facebook' %}" class="btn btn-danger mt-2 fa fa-facebook"></a>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    
</body>
</html>

dashboard.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
</head>
<body>
    <h1>Welcome to Dashboard</h1>
    <a class="btn btn-danger" href="{% url 'logout' %}">Logout</a>

</body>
</html>

Step 5: Running Django Project

To run your Django project with Facebook login functionality, execute the following command in your terminal:

python manage.py runserver

Access the site using the following URL: http://localhost:8000/

Conclusion

In summary, Incorporating a Facebook social login is an easy, yet powerful way to improve user convenience and engagement on your Django projects. Streamline registration, increase user engagement, and enhance your application’s user experience with this seamless authentication solution.

Categories: Django How To NLP Python

One Reply to “Django + Facebook Authentication: Elevate Your App’s Security with This Comprehensive Guide”

  1. Thanks!

Leave a Reply

Your email address will not be published.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*