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

10% refund of hotel reservation amount on Booking
10% refund of hotel reservation amount on Booking
We offer a link with a 10% return on the amount of the order when booking a hotel through Booking
  • #
  • 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
ГК
March 20, 2019, 9:01 a.m.
Геннадий Костоянский

C++ - Test 002. Constants

  • Result:0points,
  • Rating points-10
ГК
March 20, 2019, 8:46 a.m.
Геннадий Костоянский

C++ - Test 002. Constants

  • Result:25points,
  • Rating points-10
Last comments
MU
March 20, 2019, 3:43 p.m.
Maciej Urmański

It's possible to simply add vote option for non logged users?
March 20, 2019, 9:45 a.m.
Евгений Легоцкой

Добрый день. Поппробуйте домен localhost, а url соответственно http://localhost Возможно, потребуется указать порт. Например, так http://localhost:8000
March 19, 2019, 12:57 p.m.
AlexanderBardin

Добрый день. А проверить работоспособность локально как-то можно не указывая реальнй сайт (еще в разработке)
March 16, 2019, 1:55 p.m.
Дмитрий

Спасибо за статью. Давно итересует следующий вопрос: с помощью переменных QMAKE_TARGET_COMPANYQMAKE_TARGET_PRODUCTQMAKE_TARGET_DESCRIPTIONможно задать свойства компилируемой программы, о...
JS
March 12, 2019, 10:19 a.m.
Jean Stefanovich

Большое спасибо за разъяснения!
Now discuss on the forum
March 20, 2019, 12:26 p.m.
Евгений Легоцкой

Лучше стараться избегать этого. Нормального механизма нет. Я просто выдёргиваю из бэкенда перевёденные куски шаблона, если нужно что-то задействовать в JS.
March 17, 2019, 10:47 p.m.
Евгений Легоцкой

Добрый день. Вот, нашлось у меня немного времени. Делается это через шаблон проектирования наблюдатель. GraphKS_mfvSlup.zip
ЧГ
March 15, 2019, 9:52 p.m.
Чарльз Грин

спасибо, попробую, отпишусь
m
March 15, 2019, 7:41 p.m.
mihamuz

Сори догадался)
n
March 12, 2019, 4:57 p.m.
newbie.works.with.QT

Большооооое спасибо!!!!!Не передать как я вам благодарен, спасибо что всегда отзываетесь.Теперь я смогу продолжить работу в QT!!! (пробую писать бота (Я как вы могли догадаться немного не пр...
Join us in social networks

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