django -- Azure AD应用程序
登录注册
首先登录注册一个账号,如果有账号直接登录,没有需要注册 portal.azure.com/home
仔细阅读文档
这里强调一下阅读文档的重要性,本人就是受了之前申请人员推荐的认证方式的亏,导致后期各种东西不通,只能自己有苦自己知道啊
docs.microsoft.com/zh-cn/azure…
创建应用-> 添加平台 -> 获取秘钥等信息
我们这里因为是后端去处理的登录操作,因此要选择web 之前申请的时候因为不是很了解,先申请了一个单页应用程序,导致后来调用不通,排查半天发现原来问题在这里,然后又重新申请的账号,进行对接
处理逻辑部分
代码目录结构
aad.config.json 主要配置文件
{ "type": { "client_type": "CONFIDENTIAL", "authority_type": "SINGLE_TENANT", "framework": "DJANGO" }, "client": { "client_id": "客户端ID", "client_credential": "申请的客户端秘钥", "authority": "https://login.microsoftonline.com/目录ID" }, "auth_request": { "redirect_uri": null, "scopes": [], "response_type": "code" }, "flask": null, "django": { "id_web_configs": "MS_ID_WEB_CONFIGS", "auth_endpoints": { "prefix": "auth", "sign_in": "sign_in", "edit_profile": "edit_profile", "redirect": "redirect", "sign_out": "sign_out", "post_sign_out": "post_sign_out" } } }复制代码
urls.py
from django.urls import path, include from . import views from django.conf import settings from django.conf.urls.static import static from ms_identity_web.django.msal_views_and_urls import MsalViews msal_urls = MsalViews(settings.MS_IDENTITY_WEB).url_patterns() urlpatterns = [ path('', views.index, name='index'), path('sign_in_status', views.index, name='status'), # path('auth/redirect', views.get_token, name='token'), path('token_details', views.token_details, name='token_details'), path(f'{settings.AAD_CONFIG.django.auth_endpoints.prefix}/', include(msal_urls)), *static(settings.STATIC_URL, document_root=settings.STATIC_ROOT), ]复制代码
view.py
from django.shortcuts import render from django.conf import settings import requests ms_identity_web = settings.MS_IDENTITY_WEB def index(request): return render(request, "auth/status.html") def get_token(request): return render(request, "auth/status.html") @ms_identity_web.login_required def token_details(request): return render(request, 'auth/token.html') @ms_identity_web.login_required def call_ms_graph(request): ms_identity_web.acquire_token_silently() graph = 'https://graph.microsoft.com/v1.0/me' # 获取本人信息接口客户获取登录用户的信息 authZ = f'Bearer {ms_identity_web.id_data._access_token}' results = requests.get(graph, headers={'Authorization': authZ}).json() # trim the results down to 5 and format them. if 'value' in results: results['num_results'] = len(results['value']) results['value'] = results['value'][:5] return render(request, 'auth/call-graph.html', context=dict(results=results))复制代码
根据以上几个接口就可以在后端验证人员信息并登录到你的服务啦,最后再说说一句,请先看文档再进行开发切记
作者:劲风君
链接:https://juejin.cn/post/7025780602540392461