Evgenii Legotckoi
Evgenii LegotckoiJuly 16, 2018, 3:15 a.m.

Django - Tutorial 037. How to add authentication through social networks. Google+

The second social network through which you can authenticate on the site will be Google+.

I will not go into all the details of setting up and installing the Python Social Auth Django battery, as it was discussed in the previous article . But I note that this time the connection took only half an hour.

However, setting up access through the Google API was more complex than for VKontakte.


settings.py

First, you need to register a new backend, which will be responsible for authenticating via Google+.

AUTHENTICATION_BACKENDS = (
    ...
    'social_core.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

Secondly, you need to write the variables for the API key and private key

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'XXXXXXXX'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'XXXXXXXXX'

Setting up the application in the Google API Console

And now we'll figure out how to configure the application in the Google API Console to gain the ability to authenticate users on the site through the Google+ social network.

Step 1 - create a project

Step 2 - Enable the Google+ API

After your project is created, you need to connect the appropriate API, namely the Google+ API.

Go to the Enable API and Services section.

Find the Google+ API and enable it

Step 3 - Create a website application in your project

You need to go to the credentials section and select the OAuth customer ID item in the user credentials creation box.

From the options offered, select the Web application.

Step 4 - Configuring the Credential Query page

Here you will be asked to choose your email address. as a developer, you can add and some other.

Next is the name of the product.

And the URL of the main page of your site, the rest at will

Step 5 - Set up the app's access to the Google+ API

Unlike VKontakte, in the case of the Google+ API, it is controlled more thoroughly where the request comes from and where the user is redirected in case of successful authorization. Here lies one nuance of customization.

Here in these settings are the keys we need

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'Идентификатор клиента'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'Секрет клиента'

Then sources and redirects.

In the permitted sources you need to show the address of your site, for example

https://example.com

But the permissible URI redirection implies where the user should be redirected in case of successful authentication. And here you need to consider how you have connected the social authentication module on the site. In my case, it is connected to the root of the site, so you get this address

http://example.com/complete/google-oauth2/

If this is not set, then authentication will not work properly, because the Google+ API will not allow the user to successfully navigate to your site with authentication data.

Template

In the template, you can add this code to get the icon from the authorization url

<a href="{% url 'social:begin' 'google-oauth2' %}"><img src="/static/lgoogle.png" class="avatar-3" data-toggle="tooltip" title="{% trans 'Login via Google+' %}"></a>

Authenticating a user from different social networks

It may also be a problem to determine a user if he is logged into an account on the site using different social networks, for example, today he came through VKontakte, and tomorrow he will use Google+.

Then, so that several accounts of the same user do not appear, you need to check the information about the user who is authenticated with the help of the social network, and if he already visited the site with the help of another social network earlier, then link his authentication with the earlier created account.

This check is included in Python Social Auth Django in one setting.

SOCIAL_AUTH_PIPELINE = (
    'social_core.pipeline.social_auth.associate_by_email',
)

In this case, information about the user's email is used

For Django I recommend VDS-hosting TIMEWEB

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Владислав Меленчук
  • July 29, 2021, 2:49 a.m.

Какую ссылку в гулге юзать для редиректа oauth2?

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 11:56 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 11:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 11:35 a.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 12:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 2:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 1:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 9:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 11:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks