Here is a step-by-step tutorial for integrating Facebook login in Django:
Step 1: Create a Facebook App and Get Credentials
To use Facebook Login in your Django app, you'll first need to create a Facebook app and get your app ID and app secret key. Follow these steps:
- Go to the Facebook Developers website and create a new app.
- Choose "Website" as the platform and enter your website URL.
- Go to the "Settings" tab and enter your app name and contact email.
- Go to the "Add a Product" tab and select "Facebook Login."
- Under "Settings," enter your app domain and redirect the URL.
- Go to the "Settings" tab and copy your App ID and App Secret.
Step 2: Install Facebook SDK and Django-Allauth
Next, you'll need to install the Facebook SDK and Django-allauth, which is a third-party package that makes it easy to add social authentication to Django apps. You can install both packages using pip:
pip install facebook-sdk
pip install django-allauth
Step 3: Configure Django-Allauth
In your Django project's settings.py file, add the following lines to enable Django-allauth and configure it to use Facebook:
# settings.py
INSTALLED_APPS = [
# ...
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
# ...
]
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
'METHOD': 'oauth2',
'SCOPE': ['email', 'public_profile', 'user_friends'],
'AUTH_PARAMS': {'auth_type': 'reauthenticate'},
'INIT_PARAMS': {'cookie': True},
'FIELDS': [
'id',
'email',
'name',
'first_name',
'last_name',
'verified',
'locale',
'timezone',
'link',
'gender',
'updated_time',
],
'EXCHANGE_TOKEN': True,
'LOCALE_FUNC': lambda request: 'en_US',
'VERIFIED_EMAIL': False,
'VERSION': 'v12.0',
}
}
SITE_ID = 1 # Or the site ID for your Django project
This configures Django-allauth to use Facebook for social authentication and specifies the fields to retrieve from Facebook's API.
Step 4: Add Login URL to Facebook App
In your Facebook app's settings, add the following URL as a valid OAuth redirect URL:
https://<your-domain>/accounts/facebook/login/callback/
Step 5: Add Facebook Login Button to Your Django Templates
Finally, you can add a Facebook Login button to your Django templates using the Django-allauth template tags. Here's an example:
{% load socialaccount %}
{% providers_media_js %}
<a href="{% provider_login_url 'facebook' next='/success/' %}">Login with Facebook</a>
This code loads the required JavaScript files and displays a button that redirects the user to Facebook's login page when clicked.
That's it! With these steps, you should be able to integrate Facebook Login into your Django app using Django-allauth.