Evgenij LegotskojJuly 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.
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting
b

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
US

C++ - Test 005. Structures and Classes

  • Result:91points,
  • Rating points8
US

C++ - Test 002. Constants

  • Result:33points,
  • Rating points-10
Last comments
t

Qt/C++ - Lesson 013. QMenu – How to work with context menu in QTableView?

Добрый день, в строке 49 файла mainwindow.cpp создаётся меню и оно будет создаваться каждый раз при его вызове. Т.е. каждый раз будет выделяться память под QMenu. Это же утечка памяти или Q…
TF

Qt/C++ - Lesson 054. Reading data from a CSV file, and their representation via QStandardItemModel

А если мне надо данными из файла подписать оси x и y и построить график как это сделать?

QML - Lesson 018. Loader in QML Qt – The working with the dynamic components

Лично для меня loader - это компонень, который загружает какую-то часть внутри окна, поэтому с этой точки зрения я бы не стал рассматривать использование loader лоя открытия окон, только для зап…
KF

QML - Lesson 018. Loader in QML Qt – The working with the dynamic components

добрый день, грамотно ли использовать loader для загрузки небольших диалоговых окон по клику из меню? и если да, то возникает проблема: загрузили первое диалоговое окно, потом его закрыли, а отк…
Q
  • QISHON
  • July 16, 2021, 6:28 a.m.

Data encryption by RSA algorithm in Qt with public and private keys without binding to OpenSSL

Возможно ли с помощью этой библиотеки шифровать файлы, а не обычные строки?
Now discuss on the forum

QScrollArea dynamically add QCheckBoxes

Всё правильно. Это просто спамер, который отправился в вечный бан.
IP

Как совместить таблицу и дерево в Qt

Необходимо использовать виджет QTreeView, для него необходимо сделать соответствующую модель. Примеры есть в самом Qt
K

Как поменять шаг оси с числового формата на текстовый

Добрый день. Только начинаю знакомство с Qt, а именно с библиотекой QCustomPlot. Столкнулся с такой проблемой - не знаю как поменять оси с числового на текстовый формат как на скрине. …

QWebEngineView получить событие фокуса для полей редактирования

от QWebEngineView возможно это и не получите, посмотрите в сторону WinApi для получения данного события

С++ и qml передача модели

для отображения данных нужно использовать, в вашем случае, ListModel тыц и тыц , можно представить модель классом с++ и в qml его подгружать. а для загрузки страниц использ…
About
Services
© EVILEG 2015-2021
Recommend hosting TIMEWEB