Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB

Django - Tutorial 036. How to add authentication through social networks. VKontakte

django, Social

On the recommendation of users of the site began to add authentication through social networks to the site. The first such social network was VKontakte, as the most popular social network among users of my site.

Django itself has the necessary functionality to work with the OAuth 2.0 protocol, which could be used in the VKontakte API to authenticate users on third-party resources (and not only for authentication). But in this case I did not write my bicycle using bare OAuth support in Django, but found a very good battery, which is probably well known among developers of Django sites, which allowed to introduce authentication via VKontakte in just a couple of hours.

This battery is named Python Social Auth Django .

Let's take a step-by-step look at what we need to do to connect authentication via VKontakte to the site with Django

Step 1 - Installing of Python Social Auth Django

This is done by one command in your virtual environment through the utility pip

pip install social-auth-app-django

The documentation suggests configuring two versions of the ORM for the authentication system through social networks. This is the classical ORM of Django and ORM MongoEngine, but it turned out that the package required for MongoEngine is outdated and slightly incompatible with the latest versions of Django, it just does not work, even in the mongoengine developer documentation there is a call for help with the utility's support. Therefore, we will adjust only for the classical ORM.

Step 2 - Registering a battery on your site

We register the authentication application in INSTALLED_APPS

INSTALLED_APPS = (
    ...
    'social_django',
    ...
)

Step 3 - Database Migration

You will need to apply changes to the database structure, since this battery has its own tables to work with user authentication.

./manage.py migrate

Next, we'll follow one more recommendation for configuring the database, if you, like me, use PostgreSQL. Namely...

When using PostgreSQL, it is recommended to use the built-in JSONB field to store the extracted extra data. To enable it, set the following:

SOCIAL_AUTH_POSTGRES_JSONFIELD = True

Step 4 - Configuring authentication backends

Also write in settings.py

AUTHENTICATION_BACKENDS = (
    'social_core.backends.vk.VKOAuth2',          # authentication backend via VKontakte
    'django.contrib.auth.backends.ModelBackend', # classic authentication backend, so that authentication works through a common username and password
)

Be sure to enable the classical authentication backend, otherwise you will lose the ability to log in through the login and password to the site.

Step 5 - Configuring the template engine

I have a year and a half of developing this site, the TEMPLATES setting has remained virtually untouched, but I added one line for this battery

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',
                'social_django.context_processors.backends', # Добавил эту строку
            ],
        },
    },
]

Step 6 - Setting up the keys for VKontakte

Here is the setting of secret keys for VKontakte

SOCIAL_AUTH_VK_OAUTH2_KEY = 'XXXXXXX'
SOCIAL_AUTH_VK_OAUTH2_SECRET = 'XXXXXXXXXXXXXXXXXXXX'

To get them, you need to create an application in the developer's VKontakte toolkit and take the ID of your application and the secret key for it.

Register the application

We go into its settings and see everything that is needed

As a result, we assign the following settings to these variables:

SOCIAL_AUTH_VK_OAUTH2_KEY = 'ID приложения'
SOCIAL_AUTH_VK_OAUTH2_SECRET = 'Защищённый ключ'

Step 7 - Connecting routes for authentication in urls.py

This is done in this way

urlpatterns = [
    ...
    path('', include('social_django.urls')),
]

Step 8 - Adding a link to a route

And now add a link to the route somewhere in the template to run authentication via VKontakte

<a href="/login/vk-oauth2"><img src="/static/lvk.png" class="avatar-3" data-toggle="tooltip" title="{% trans 'Login via VKontakte' %}"></a>

Step 9 - Configure redirect for authentication

This is an optional setting that specifies the URL for redirecting the user to your page after successful authentication. Leave the root of the site

LOGIN_REDIRECT_URL = '/'

There already will understand, as it is better for you to do

Step 10 - Requesting permissions to access the email

I have my own mail notification system on the site, so it's important for me to have access to the email user to notify him of new events on the resource, so we'll add a request to access the email.

SOCIAL_AUTH_VK_OAUTH2_SCOPE = ['email']

For Django I recommend VDS-hosting TIMEWEB

  • #
  • July 14, 2018, 4:17 a.m.

Мне интересно что будет если в обеих сетях в авторизации одинаковый еmail. Не выведет ли ошибку ?

Не, не будет, в данной батарейке уже есть необходимый функционал по разрулированию этой проблемы. Аутентификации из разных социальных сетей будут сливаться на один аккаунт. Так что всё нормально должно быть.

В следующей статье будет описан этот момент. Опубликую статью в понедельник.
  • #
  • Aug. 7, 2018, 4:10 a.m.

интересно можно ли через эту батарейку получить данные на данные в вк(друзья, фото итд)

Там можно запросить доступ к тому или иному функционалу, а вот полное использование API, как я понимаю, потребует либо дописывания функционала, или использование ещё каких-нибудь батареек

Нашёл ошибку в вашем примере

какая именно? написали бы сразу ))

Comments

Only authorized users can post comments.
Please, Log in or Sign up
v
Jan. 17, 2019, 11:51 a.m.
vitalir12

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

  • Result:20points,
  • Rating points-10
v
Jan. 17, 2019, 11:49 a.m.
vitalir12

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
v
Jan. 17, 2019, 11:13 a.m.
vitalir12

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

  • Result:28points,
  • Rating points-10
Last comments
I
Jan. 16, 2019, 8:06 a.m.
IscanderChe

Заработало. Забыл model->select(); вписать.
I
Jan. 16, 2019, 8:02 a.m.
IscanderChe

Всё равно пусто, хотя строка с данными в базу добавляется.
Jan. 16, 2019, 7:51 a.m.
Евгений Легоцкой

потому, что нужно сохранять информацию для всех остальных ролей и столбцов через вызов переопределённого метода. Да к тому же вы ещё и зациклили вызов метода data. QVariant MySqlTableModel:...
I
Jan. 16, 2019, 7:43 a.m.
IscanderChe

Сделал вот так. В tableView ничего нет, кроме заголовка. QVariant MySqlTableModel::data(const QModelIndex &index, int role) const{ if (role == Qt::DisplayRole) { QTime ...
Now discuss on the forum
Jan. 18, 2019, 11:26 a.m.
nayk1982

Для Desktop делал так: void pause(int ms){ QTimer timer; timer.setInterval( qBound(1, ms, 3600000) ); timer.setSingleShot(true); QEventLoop loop; QObject::connect(&...
Jan. 17, 2019, 12:01 p.m.
Алексей Внуков

у меня просто есть отдельное поле с чекбоксамими какие колонки нужно отображать CheckBox { id: checkBox text: qsTr("some text") checked: true onC...
Jan. 15, 2019, 4:53 p.m.
Михаиллл

Спасибо, заработало.Но выдало обычный текст без форатирования HTML.Придется искать дальше
Jan. 15, 2019, 12:52 p.m.
BlinCT

Я же вам выше написал CLion умеет работать с ремоут машинами. И Qt так же собирает.
Join us in social networks

For registered users on the site there is a minimum amount of advertising