集成 python-social-auth (social-app-django) 与 Django 管理一起使用

Integrate python-social-auth (social-app-django) to be used with the Django admin

我想创建一个使用 django admin 的应用程序,但允许通过 google(我公司 google 帐户)代替 django 默认 ModelAdmin 登录。

目前,它看起来像 social-app-django (google) is the way to go, but after having installed and setup a project, it's not clear to me how I can allow django admin logins to use the social-app-django authentication. I've attempted to configure my project as described here http://python-social-auth.readthedocs.io/en/latest/configuration/django.html,但不清楚如何将其与 django 管理集成。

我找到了这个 snippit(似乎 过时了 ),并添加了它,但是当我尝试转到 /admin/:

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/admin/login/%3Fnext%3D/admin/ Using the URLconf defined in telos.urls, Django tried these URL patterns, in this order: ^login/(?P[^/]+)/$ [name='begin'] ^complete/(?P[^/]+)/$ [name='complete'] ^disconnect/(?P[^/]+)/$ [name='disconnect'] ^disconnect/(?P[^/]+)/(?P[^/]+)/$ [name='disconnect_individual'] ^admin/ The current path, accounts/login/, didn't match any of these.

如果我删除代码片段,/admin/ 将重定向到 /admin/login/ 并在尝试登录时 return 错误文本:

Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.

除了 configuration,我还在我的 settings.py 中添加了以下内容:

projects/models.py (MyUser)

from django.contrib.auth.models import AbstractUser

class MyUser(AbstractUser):
    pass

settings.py

# for identification of SOCIAL_AUTH_USER
# http://python-social-auth.readthedocs.io/en/latest/configuration/settings.html#user-model
SOCIAL_AUTH_USER_MODEL = 'projects.MyUser'
AUTH_USER_MODEL = 'projects.MyUser'  # not sure if this is needed

任何人都可以指导我如何设置我的项目以允许我通过 social-app-django (google) 登录到 django 管理员吗?

Django Admin 使用 auth contrib 应用程序,因此任何身份验证过程都会触发与用户登录到非管理部分相同的机制,如果 python-social-auth 后端在 AUTHENTICATION_BACKENDS 设置中定义。

为了使其正常工作,您需要:

  1. 在登录表单中添加 Login with Google link(linking 到 /login/google-oauth2)。您可以通过添加 admin/login.html template or by defining a custom AdminSite
  2. 来覆盖默认登录表单
  3. 确保用户被标记为is_staff,否则将禁止访问管理员。