如何使用现有ASP.Net IdentityServer登录应用实现Django应用用户认证?求相关示例代码与教程
别担心,Django完全能搞定对接IdentityServer4的认证,根本不用局限在JS应用上!我刚帮朋友做过类似的需求,给你一步步拆解,包括你最困惑的回调环节,还有必须用到的工具包。
核心前提:用OpenID Connect客户端包
你确实需要用OpenID客户端包来简化流程,Django生态里最成熟的就是**mozilla-django-oidc**,它帮我们封装了OIDC认证的所有细节,包括回调处理、令牌交换这些复杂逻辑。
第一步:安装依赖
先通过pip安装这个包:
pip install mozilla-django-oidc
第二步:配置Django Settings.py
打开你的settings.py,做以下配置:
1. 添加应用到INSTALLED_APPS
INSTALLED_APPS = [ # 你的其他应用... 'mozilla_django_oidc', ]
2. 配置OIDC核心参数
替换成你自己的IdentityServer地址和客户端信息:
# IdentityServer相关配置 OIDC_RP_CLIENT_ID = "django-client" # 你在IdentityServer里注册的客户端ID OIDC_RP_CLIENT_SECRET = "your-client-secret-here" # 客户端密钥 OIDC_OP_AUTHORIZATION_ENDPOINT = "http://your-identityserver-url/connect/authorize" OIDC_OP_TOKEN_ENDPOINT = "http://your-identityserver-url/connect/token" OIDC_OP_USERINFO_ENDPOINT = "http://your-identityserver-url/connect/userinfo" OIDC_OP_JWKS_ENDPOINT = "http://your-identityserver-url/connect/jwks" OIDC_RP_SIGN_ALGO = "RS256" # 要和IdentityServer的签名算法一致,一般是RS256 # 跳转配置 LOGIN_REDIRECT_URL = "/" # 登录成功后跳转到首页 LOGOUT_REDIRECT_URL = "/" # 退出后跳转的页面
3. 配置认证后端
把OIDC认证后端加入到认证体系里,也可以保留默认的Django认证(可选):
AUTHENTICATION_BACKENDS = [ 'mozilla_django_oidc.auth.OIDCAuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', # 保留本地账号登录,可选 ]
第三步:配置URL路由
在项目的urls.py里添加OIDC相关的路由,尤其是回调地址:
from django.urls import path from mozilla_django_oidc import views as oidc_views urlpatterns = [ # 你的其他路由... # OIDC登录入口 path('oidc/login/', oidc_views.OIDCAuthenticationRequestView.as_view(), name='oidc_login'), # 关键的回调地址,IdentityServer会跳回这里 path('oidc/callback/', oidc_views.OIDCAuthenticationCallbackView.as_view(), name='oidc_callback'), # OIDC退出登录 path('oidc/logout/', oidc_views.OIDCLogoutView.as_view(), name='oidc_logout'), ]
第四步:在IdentityServer里注册Django客户端
这一步是在你的.NET IdentityServer项目里配置,需要添加一个对应Django的客户端:
new Client { ClientId = "django-client", # 和Django配置里的OIDC_RP_CLIENT_ID一致 ClientName = "Django Web Application", AllowedGrantTypes = GrantTypes.Code, # 用Authorization Code流程,最适合Web应用 ClientSecrets = { new Secret("your-client-secret-here".Sha256()) }, # 和Django里的密钥一致 RedirectUris = { "http://your-django-url/oidc/callback/" }, # 必须和Django的回调路由完全一致,包括斜杠 PostLogoutRedirectUris = { "http://your-django-url/oidc/logout/" }, AllowedScopes = { "openid", "profile", "email" }, # 申请获取用户的基础信息 AllowOfflineAccess = true, # 可选,支持刷新令牌 RequirePkce = true # 开启PKCE,提升安全性,推荐开启 }
配置完后重启IdentityServer服务。
第五步:在Django模板里添加登录/退出按钮
在你的页面模板里加入登录入口和用户信息展示:
{% if user.is_authenticated %} <div class="user-info"> <p>欢迎回来, {{ user.username }}!</p> <a href="{% url 'oidc_logout' %}">退出登录</a> </div> {% else %} <a href="{% url 'oidc_login' %}">使用IdentityServer登录</a> {% endif %}
回调环节到底在干嘛?(帮你理清逻辑)
你之前困惑的回调流程,其实mozilla-django-oidc已经帮我们做了大部分工作:
- 用户点击登录链接,被重定向到IdentityServer的登录页面
- 用户输入账号密码完成登录后,IdentityServer会生成一个授权码,并跳回Django的
/oidc/callback/地址,同时把授权码带过去 - Django的回调视图自动拿着授权码,向IdentityServer的令牌端点请求访问令牌和ID令牌
- 接着调用UserInfo接口,获取用户的详细信息(比如邮箱、姓名)
- 自动在Django的User表中创建或更新对应用户,然后完成登录
- 最后跳转到你配置的
LOGIN_REDIRECT_URL地址
自定义用户处理(可选)
如果需要根据IdentityServer返回的用户信息(claims)自定义用户的创建或更新逻辑,可以继承OIDCAuthenticationBackend:
# 在你的app里创建一个auth.py文件 from mozilla_django_oidc.auth import OIDCAuthenticationBackend class CustomOIDCBackend(OIDCAuthenticationBackend): def create_user(self, claims): # 从claims中提取自定义字段,比如given_name、family_name user = super().create_user(claims) user.first_name = claims.get('given_name', '') user.last_name = claims.get('family_name', '') user.save() return user def update_user(self, user, claims): # 登录时更新用户信息 user.first_name = claims.get('given_name', user.first_name) user.last_name = claims.get('family_name', user.last_name) user.save() return user
然后在settings.py里把认证后端改成这个自定义的:
AUTHENTICATION_BACKENDS = [ 'your_app_name.auth.CustomOIDCBackend', 'django.contrib.auth.backends.ModelBackend', ]
这样整个流程就跑通了,你可以先按这个步骤试试,有问题再调整细节~
内容的提问来源于stack exchange,提问作者High Roller
相关产品推荐
相关产品推荐

