django - Django、mozilla-django-oidc 和管理员
问题描述
我正在尝试使用mozilla-django-oidc库将 Okta 与我正在编码的自定义 Django (v.3.0.2) 应用程序连接起来。到目前为止,初始用户身份验证和帐户创建(使用 Django 的用户模型)有效,但我不明白我需要做什么才能让 Django AdminSite工作。
引入之前的管理站点mozilla-django-oidc
按预期工作。我创建了一个名为“admin”的管理员用户,该用户能够登录。
要集成mozilla-django-oidc
库,我按照此处的说明进行操作:https ://mozilla-django-oidc.readthedocs.io/en/stable/installation.html 。这些说明没有具体提及 AdminSite。
当我在库集成后访问 AdminSite 时,我有以下内容:
- AdminSite 使用默认模板——我的假设是它也会使用 Okta 进行身份验证。
- 以前能够登录 AdminSite 的管理员帐户“admin”不再起作用
我的目标是能够访问 AdminSite。只要我可以访问它,我不介意它是通过 Okta 还是通过 vanilla 界面。
以下是文件中的相关部分(以便集成):
网址.py
urlpatterns = [
path('', static_site.site_index, name='site_index'),
path('admin/', admin.site.urls),
path('review/', include('review.urls')),
path('oidc/', include('mozilla_django_oidc.urls')),
]
设置.py
# OICD
AUTHENTICATION_BACKENDS = (
'mozilla_django_oidc.auth.OIDCAuthenticationBackend',
)
OIDC_RP_CLIENT_ID = 'xxxxx'
OIDC_RP_CLIENT_SECRET = 'xxxx'
OIDC_RP_SIGN_ALGO = 'RS256'
OIDC_OP_JWKS_ENDPOINT = 'https://dev-xxx.okta.com/oauth2/default/v1/keys'
OIDC_RP_SCOPES = 'openid email profile'
OIDC_OP_AUTHORIZATION_ENDPOINT = 'https://dev-xxx.okta.com/oauth2/default/v1/authorize'
OIDC_OP_TOKEN_ENDPOINT = 'https://dev-xxx.okta.com/oauth2/default/v1/token'
OIDC_OP_USER_ENDPOINT = 'https://dev-xxx.okta.com/oauth2/default/v1/userinfo'
# Provided by mozilla-django-oidc
LOGIN_URL = reverse_lazy('oidc_authentication_callback')
# App urls
LOGIN_REDIRECT_URL = reverse_lazy('review:dashboard')
LOGOUT_REDIRECT_URL = reverse_lazy('site_index')
欢迎任何想法或指点!
解决方案
我想出了一个使用 django 管理员的 mozilla-django-oidc 登录的解决方案。这有点骇人听闻,但重定向管理员登录页面比覆盖 AdminSite 少得多。
在我的顶级 urls.py 我有
class CustomLogin(View):
def get(self, request, **kwargs):
return HttpResponseRedirect(
reverse('oidc_authentication_init') + (
'?next={}'.format(request.GET['next']) if 'next' in request.GET else ''
)
)
urlpatterns = [
path('oidc/', include("mozilla_django_oidc.urls")),
path('admin/login/', CustomLogin.as_view()),
path('admin/', admin.site.urls),
# the rest of my urls...
]
如果您不关心?next=
正确传递值,则可以跳过 CustomLogin 类并改为执行以下操作
urlpatterns = [
path('oidc/', include("mozilla_django_oidc.urls")),
]
# This only works if you break up urlpatterns so the reverse below can find what it needs
urlpatterns += [
path('admin/login/', RedirectView.as_view(
url=reverse('oidc_authentication_init') + ?next=/admin/,
permanent=False
)),
path('admin/', admin.site.urls),
# the rest of my urls...
]
我添加了?next=/admin/
因为默认情况下,一旦您登录,您将被重定向到settings.LOGIN_REDIRECT_URL
我已经用于其他用途的地方
推荐阅读
- python - 在模型类上循环训练模型并按模型类更改数据框名称
- react-native - npm install -g react-native-cli - 显示错误
- java - 如何避免编写许多非常相似的 setter 方法?
- python - 带有 scipy.interpolate.ndgriddata 的网格数据中的条纹
- android - 已发送消息出现在日历中
- javascript - WordPress - 多个指向同一 URL 的菜单链接处于活动状态
- swift - 未调用 CollectionView 函数“didSelectItemAt”
- c++ - UI 正在打印中文符号而不是有效文本
- flutter - 如何在 GridView (Flutter) 中进行分页
- image - Go 生成的动画 GIF 在 Windows 中不起作用