Evgenii Legotckoi
Evgenii LegotckoiOct. 27, 2018, 7:36 p.m.

Django - Tutorial 040. How to add authentication through social networks. Facebook

I added authorization on the site through Facebook.

At the same time collected a couple of pitfalls.

Before Facebook , I already added in authorization through the social network VKontakte and Google . And here I needed to create a privacy policy page, since Facebook requires this page and also requires a user agreement, but I provided a privacy policy page. I think that with the growth of the site I will add a full-fledged page of the user agreement, although it is unknown when it will be. However, the site rules are described in sufficient detail.

Also came across a strict need for https from the site. Generally, if you consider that I have https from Let`s Encrypt , I didn’t think that there would be any problem, but as it turned out, by default django-social-auth forms the return address with HTTP protocol, and for using HTTPS You need to specify this in the settings.

And now let's see how this is done.


Application registration

To use authentication, you need to register an application. I will not go into the basic details of creating an application. But I will indicate the main settings of the application.

You will receive the application ID and the application secret key.

Specify the application domain, as well as the privacy policy URL and the user agreement URL.

And then specify the url to redirect registration through OAuth.

settings.py

Add the necessary settings to the settings.py file.

Configure the application ID and secret key. And also that we want to receive from the user profile. I only need email at this stage.

SOCIAL_AUTH_FACEBOOK_KEY = 'XXXXXXXXX'
SOCIAL_AUTH_FACEBOOK_SECRET = 'XXXXXXXXX'
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']

And also indicate that we want to use HTTPS . Otherwise, Facebook will swear.

SOCIAL_AUTH_REDIRECT_IS_HTTPS = True

We specify the Backend for authentication.

AUTHENTICATION_BACKENDS = (
    ...
    'social_core.backends.facebook.FacebookOAuth2',
    ...
)

Well, we specify the url for authentication

<a href="{% url 'social:begin' 'facebook' %}">Facebook</a>
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!

AlexanderBardin
  • March 19, 2019, 8:57 a.m.

Добрый день. А проверить работоспособность локально как-то можно не указывая реальнй сайт (еще в разработке)

Evgenii Legotckoi
  • March 20, 2019, 5:45 a.m.

Добрый день.

Поппробуйте домен localhost, а url соответственно http://localhost

Возможно, потребуется указать порт. Например, так http://localhost:8000

АБ
  • March 21, 2019, 5:35 a.m.
  • (edited)

как быть с такой ошибкой: конечный uri не внесен в белый список в разделе Клиентские настройки OAuth?

Evgenii Legotckoi
  • March 21, 2019, 5:45 a.m.

FaceBook по умолчанию направляет на https, у вас видимо http протокол. Исправьте протокол в настройках.

АБ
  • March 21, 2019, 6:06 a.m.

данная строчка у меня есть: SOCIAL_AUTH_REDIRECT_IS_HTTPS = True

АБ
  • March 21, 2019, 6:07 a.m.

адрес сайта uri перенасправления пишу так: https://мойсайт.site/

АБ
  • March 21, 2019, 6:17 a.m.

где брать действительный uri перенаправления?

Evgenii Legotckoi
  • March 21, 2019, 6:46 a.m.

Вы у себя urls прописывали?

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

В статье по настройке авторизации для ВКонтакте есть базовый мануал .

АБ
  • March 21, 2019, 7:02 a.m.
  • (edited)

Да, конечно VK работает, настраивал по вашему мануалу, а тут прям какойто ступор: https://amadowshop.site/auth/register/

Evgenii Legotckoi
  • March 21, 2019, 7:04 a.m.
  • (edited)

Вы прописывали url в действительные uri перенаправления так?

https://amadowshop.site/complete/facebook/

АБ
  • March 21, 2019, 7:15 a.m.

прописал, та же ошибка ...(((

Evgenii Legotckoi
  • March 21, 2019, 7:25 a.m.

ох тыж, как глубоко запихали авторизацию.

У вас по ходу такой url формируется

https://amadowshop.site/auth/verify/vk/oauth2/complete/facebook/

АБ
  • March 21, 2019, 7:35 a.m.

да, спасибо, этот урл зарабтал, методом перебеора в итоге поймал )))
https://amadowshop.site/auth/verify/vk/oauth2/complete/facebook/

Evgenii Legotckoi
  • March 21, 2019, 7:38 a.m.

ну я просто глянул у вас страницу авторизации и обнаружил, что вы очень глубоко запихали include('social_django.urls')

А вообще, вот эта часть выглядит некрасиво в вашем url auth/verify/vk/oauth2/ . Наличие упоминания vk там вообще ни к чему

АБ
  • March 21, 2019, 8:26 a.m.

url подкорректировал, но теперь ошибка и адрес сменился на https://amadowshop.site/auth/verify/login/facebook/

Evgenii Legotckoi
  • March 21, 2019, 8:47 a.m.

не вижу здесь проблемы, поменяйте url для callback в приложения oauth в социальных сетях

https://amadowshop.site/auth/verify/complete/facebook/

АБ
  • March 21, 2019, 11 a.m.

а это где? сейчас ошибка в debag такая:
Page not found (404)
Request Method: GET
Request URL: http://amadowshop.site/accounts/profile/

Evgenii Legotckoi
  • March 21, 2019, 11:49 a.m.

серьезно? Эта ошибка 404 уже даже не относится к данному вопросу.

В каких-то urls в вашем проекте.

Вопросы, которые не относятся непосредственно к статье, задавайте, пожалуйста на форуме . Оффтопы не нужно делать.

Comments

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

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

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

C++ - Test 002. Constants

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

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

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 8, 2024, 3:43 p.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, 7:30 a.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, 5:38 a.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. 18, 2023, 6:01 p.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, 2:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 4:45 a.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, 3:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 13, 2024, 11:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 1:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks