Django social auth demo
This example explains how to authorize via Facebook in Django using OAuth2. Note that Django 1.10
used, some options in settings.py
may differ in older versions.
Register facebook application and get keys
Go to https://developers.facebook.com/apps/, press:
Add Facebook Login
product, go to Settings
and add http://djsoc.local:8000/complete/facebook
Note thatlocalhost:8000
or127.0.0.1:8000
can't be used, butdjsoc.local:8000
is ok
Go to Dashboard and see your App ID
and App Secret
, you will need to use them in settings.py
Configure Django
Install social-auth-app-django
pip install social-auth-app-django
Add to the end of settings.py
:
# CUSTOM PARAMETERS
ALLOWED_HOSTS += ['djsoc.local']
INSTALLED_APPS += (
'social_django',
)
SOCIAL_AUTH_FACEBOOK_KEY = 'YOUR_APP_ID'
SOCIAL_AUTH_FACEBOOK_SECRET = 'YOUR_APP_SECRET'
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
'locale': 'ru_RU',
'fields': 'id, name, email, age_range'
}
AUTHENTICATION_BACKENDS = (
'social_core.backends.facebook.FacebookOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
TEMPLATES[0]['OPTIONS']['context_processors'] += [
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
]
Modify main urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic.base import TemplateView
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', TemplateView.as_view(template_name='main.html')),
url(r'^logout/', auth_views.logout, name='logout'),
url('', include('social_django.urls', namespace='social')),
]
Add template main.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django Social Auth demo</title>
</head>
<body>
You logged in as: {{ request.user }}
<br>
<a href="{% url "social:begin" "facebook" %}?next={{ request.path }}">Auth via Facebook</a>
<br>
<a href="{% url "logout" %}?next=/" >Logout</a>
</body>
</html>
Running
Add djsoc.local
to hosts
:
echo "127.0.0.1 djsoc.local" >> /etc/hosts
Migrate and run server
python manage.py migrate manage.py runserver djsoc.local:8000
Ready for production?
After you test all staff go to App Review
tab and make app public