24
loading...
This website collects cookies to deliver better user experience
pip install social-auth-app-django
INSTALLED_APPS = [
# ...
'social_django',
]
social_django
app.python manage.py makemigrations
python manage.py migrate
AUTHENTICATION_BACKENDS = (
'social_core.backends.github.GithubOAuth2',
'social_core.backends.google.GoogleOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
django.contrib.auth.backends.ModelBackend
is the basic authentication backend which comes by default in django to let users login by username/password method. The ones above it are Google and Github backends to use within our app for social authentication.TEMPLATES
list and add the following to context_processors
.TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
# Add the following two
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
},
},
]
Whenever a template is rendered with a request, a context is also returned. Imagine we are building an app where we have to include the same data in every view we create. It is hard and prone to error right. This is where context processors come in to play. context_processors
contains a list of paths to callables which will return a dictionary to be merged with context of each view saving us the trouble of having to add the same data over and over again.
Okay, let's move on to the next part which is updating the project's urls.py module to include the social auth app's urls.
# add the following imports
from django.urls import path, include
from django.conf.urls import url
urlpatterns = [
# add this new url entry to include the social auth's urls
url(r'^oauth/', include('social_django.urls', namespace='social')),
]
# social auth configs for github
SOCIAL_AUTH_GITHUB_KEY = 'YOUR GITHUB KEY'
SOCIAL_AUTH_GITHUB_SECRET = 'YOUR GITHUB SECRET KEY'
href
attribute that has a dead link to sign in with Github and update it as follows.<a href="{% url 'social:begin' 'github' %}" class="btn btn-link btn-lg active btn-block">Sign in with GitHub</a>
Authorized redirect URIs is where users will be redirected to after they are authenticated.
# social auth configs for google
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'YOUR GOOGLE KEY'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'YOUR GOOGLE SECRET KEY'
<a href="{% url 'social:begin' 'google-oauth2' %}" class="btn btn-link btn-lg active btn-block">Sign in with Google</a>
python manage.py runserver
in your terminal.