如何用Python实现属性收集事件的自定义身份验证扩展并适配Azure Function?
Python版Azure Function适配自定义身份验证扩展方案
一、是否存在适配方案?
是的,虽然微软官方文档仅提供C#示例,但完全可以基于Python版Azure Function实现自定义身份验证扩展:
- Azure Functions的Python运行时支持HTTP触发函数,只需遵循Entra ID自定义扩展属性收集流程的请求/响应格式,即可完成对接,与技术栈无关。
- 你需要实现两个核心逻辑:处理属性收集的
start事件(返回需要用户填写的字段)、处理submit事件(验证并存储用户提交的数据)。
二、创建属性收集Start事件的Python函数
1. HTTP触发函数基础结构
import azure.functions as func import json def main(req: func.HttpRequest) -> func.HttpResponse: try: req_body = req.get_json() event_type = req_body.get('eventType') if event_type != 'Start': return func.HttpResponse("Invalid event type", status_code=400) # 构建需要用户填写的属性字段 response = { "version": "1.0.0", "action": "Continue", "displayControls": [ { "displayControlType": "TextBox", "id": "customDepartment", "label": "请填写所在部门", "isRequired": True, "placeholder": "例如:技术部" }, { "displayControlType": "DropdownSingleSelect", "id": "customRole", "label": "请选择角色", "isRequired": True, "options": [ {"value": "admin", "label": "管理员"}, {"value": "user", "label": "普通用户"} ] } ] } return func.HttpResponse( json.dumps(response), mimetype="application/json", status_code=200 ) except Exception as e: return func.HttpResponse(f"Error processing request: {str(e)}", status_code=500)
关键注意事项
- 必须严格遵循官方定义的响应格式,包括
version、action、displayControls等核心字段。 displayControls支持TextBox、DropdownSingleSelect等多种类型,可根据需求配置必填项、选项列表等参数。
三、创建属性收集Submit事件的Python函数
1. HTTP触发函数基础结构
import azure.functions as func import json def main(req: func.HttpRequest) -> func.HttpResponse: try: req_body = req.get_json() event_type = req_body.get('eventType') if event_type != 'Submit': return func.HttpResponse("Invalid event type", status_code=400) # 提取用户提交的属性数据 submitted_attrs = req_body.get('data', {}).get('attributes', {}) department = submitted_attrs.get('customDepartment') role = submitted_attrs.get('customRole') # 自定义验证逻辑示例 if not department or len(department) < 2: return func.HttpResponse( json.dumps({ "version": "1.0.0", "action": "ShowError", "errorMessage": "部门名称长度不能少于2个字符" }), mimetype="application/json", status_code=200 ) # 验证通过后,可将数据存储到数据库或其他服务 print(f"用户提交数据:部门={department},角色={role}") # 返回成功响应,允许继续身份验证流程 return func.HttpResponse( json.dumps({ "version": "1.0.0", "action": "Continue" }), mimetype="application/json", status_code=200 ) except Exception as e: return func.HttpResponse(f"Error processing request: {str(e)}", status_code=500)
关键注意事项
- Submit事件请求会携带用户填写的
attributes数据,需提取后完成自定义验证。 - 支持返回两种
action:ShowError(向用户展示错误提示)、Continue(继续身份验证流程),根据验证结果选择即可。
四、Entra ID端配置要点
- 在Entra ID门户创建自定义扩展,选择属性收集类型。
- 将Start事件的回调URL指向你的Python Azure Function的HTTP触发地址。
- 将Submit事件的回调URL指向对应Python Function的地址(也可在同一个函数内通过
eventType区分处理逻辑)。 - 确保函数的访问权限配置正确,允许Entra ID服务请求访问(可使用Azure AD身份验证或IP限制)。
内容的提问来源于stack exchange,提问作者aka
相关产品推荐
相关产品推荐

