Authenticate Google with Django

Authenticate Google with Django

Log in to Django using your Google account instead of your own. I didn't understand it even after reading the ReadMe of the module to be used, so make a note.

What to use

The version is the one I used.

procedure

It is assumed that python manage.py runserver is ready to run. Also, make sure that you have already created a google app and obtained an ID and secret key.

First, install python-social-auth pip install python-social-auth

Then write the settings to settings.py and urls.py.

Add the following to project / setting.py

INSTALLED_APPS = (
   ...
   'social.apps.django_app.default',
   ...
)

TEMPLATE_CONTEXT_PROCESSORS = (
   'django.contrib.auth.context_processors.auth',
   'django.core.context_processors.debug',
   'django.core.context_processors.i18n',
   'django.core.context_processors.media',
   'django.core.context_processors.static',
   'django.core.context_processors.tz',
   'django.contrib.messages.context_processors.messages',
   'social.apps.django_app.context_processors.backends',
   'social.apps.django_app.context_processors.login_redirect',
)

AUTHENTICATION_BACKENDS = (
   'social.backends.facebook.FacebookOAuth2',
   'social.backends.google.GoogleOAuth2',
   'social.backends.twitter.TwitterOAuth',
   'django.contrib.auth.backends.ModelBackend',
)

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'your secret id'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'your secret key'

project_name/urls.py

urlpatterns = patterns('',
...
url('', include('social.apps.django_app.urls', namespace='social')),
url('', include('django.contrib.auth.urls', namespace='auth')),
...
)

Next, we will edit the template. This time, we will replace the login / user registration on the management screen with Google authentication.

First, create a login screen for the management screen and override it with the existing one.

Create templates / admin / login.html and select this file Please copy and paste. Rewrite the content block in the copied file. (Originally, it seems to override login.html not entirely, but partially, but I don't know, so I'm overriding the whole ...)

{% block content %}
  <center>
  {% if user and not user.is_anonymous %}
     <h1><a href="{% url 'auth:logout' %}?next={{ request.path }}">Logout</a></h1>
  {% else %}
      <h1><a href="{% url 'social:begin' 'google-oauth2' %}?next={% url 'admin:index' %}">Login with Google</a></h1>
  {% endif %}
      </center>
{% endblock %}

That's all for the procedure. Let's actually run it and check it. Below is a list of points that are easy to stumble.

login.html cannot be overridden

Invalid ~ is displayed by google authentication

That's it. Since I wrote it after creating it, there may be omissions. I would appreciate it if you could let me know if you notice anything.

Other

Validate by email address

Add the following to settings.py and it's OK SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_EMAILS = ['email address'] Add the following if you want to validate with the domain of the email address instead of the email address SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['domain']

Enable staff and superuser by default

It's hard to social login to admin and see nothing, so I wanted to enable is_staff and is_superuser from the beginning, so I'll add my own function to pipeline. This time, we will rewrite is_staff and is_superuser of the created user.

project_name/custome_pipeline.py

def set_superuser(user, *args, **kwargs):
    user.is_staff = True
    user.is_superuser = True
    user.save()

After that, add the following to settings.py. The point is to insert the created process after create_user

SOCIAL_AUTH_PIPELINE = (
    'social.pipeline.social_auth.social_details',
    'social.pipeline.social_auth.social_uid',
    'social.pipeline.social_auth.auth_allowed',
    'social.pipeline.social_auth.social_user',
    'social.pipeline.user.get_username',
    'social.pipeline.user.create_user',
    'project_name.custom_pipeline.set_superuser',  #Path to the prepared function
    'social.pipeline.social_auth.associate_user',
    'social.pipeline.social_auth.load_extra_data',
    'social.pipeline.user.user_details'
)

reference

Recommended Posts

Authenticate Google with Django
How to authenticate with Django Part 2
How to authenticate with Django Part 3
Internationalization with django
CRUD with Django
Django 1.11 started with Python3.6
Upload files with Django
Development digest with Django
Output PDF with Django
Markdown output with Django
Use Gentelella with django
Twitter OAuth with Django
Getting Started with Django 1
Send email with Django
File upload with django
Use LESS with Django
Pooling mechanize with Django
Use MySQL with Django
Start today with Django
Getting Started with Django 2
Do Django with CodeStar (Python3.6.8, Django2.2.9)
Get started with Django! ~ Tutorial ⑤ ~
Test embedded software with Google Test
Minimal website environment with django
Create an API with Django
Try Google Mock with C
Do Django with CodeStar (Python3.8, Django2.1.15)
Deploy Django serverless with Lambda
Python3 + Django ~ Mac ~ with Apache
Study Python with Google Colaboratory
Getting Started with Python Django (1)
Create a homepage with django
About learning with google colab
Get started with Django! ~ Tutorial ④ ~
Getting Started with Python Django (4)
Web application creation with Django
Getting Started with Python Django (3)
Combine FastAPI with Django ORM
Get started with Django! ~ Tutorial ⑥ ~
Save tweet data with Django
Do AES encryption with DJango
Getting Started with Python Django (6)
Combine two images with Django
Mount google drive with google-drive-ocamlfuse
Access Google Drive with Python
Getting Started with Django with PyCharm
Try OpenCV with Google Colaboratory
Real-time web with Django Channels
Translate PHP_UML --help with google translate
Double submit suppression with Django
Django REST framework with Vue.js
Use prefetch_related conveniently with Django
Getting Started with Python Django (5)
Login with django rest framework
Qiita API Oauth with Django
Test Driven Development with Django Part 3
reload in django shell with ipython
Steps to develop Django with VSCode
Test Driven Development with Django Part 4
Load Django modules with an interpreter
Set up social login with Django