如何从Azure静态Web应用读取用户的Entra ID属性
获取Azure静态Web应用已认证用户更多属性的解决方案
由于前端无法直接获取访问令牌,推荐通过Azure函数后端(C#)调用Microsoft Graph API来获取用户的职位等扩展属性,前端再调用后端接口获取结果。以下是具体实现步骤:
一、后端C#实现方案
1. 配置Azure函数权限
- 在Azure门户中找到你的Azure函数,启用系统分配身份(或使用用户分配身份)。
- 为该身份添加Microsoft Graph API权限:选择委托权限
User.Read(若需读取所有用户可选User.Read.All),并完成管理员同意。
2. 安装依赖包
在Azure函数项目中安装以下NuGet包:
Install-Package Microsoft.Identity.Web.MicrosoftGraph Install-Package Microsoft.Azure.Functions.Extensions
3. 编写函数代码
创建一个受保护的HTTP触发函数,通过On-Behalf-Of(OBO)流程获取Graph访问令牌,再调用API获取用户详细信息:
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Identity.Web; using Microsoft.Graph; using System.Threading.Tasks; namespace UserProfileFunctions { public class FetchUserDetails { private readonly ITokenAcquisition _tokenAcquisition; private readonly GraphServiceClient _graphServiceClient; // 通过依赖注入获取令牌工具和Graph客户端 public FetchUserDetails(ITokenAcquisition tokenAcquisition, GraphServiceClient graphServiceClient) { _tokenAcquisition = tokenAcquisition; _graphServiceClient = graphServiceClient; } [FunctionName("FetchUserDetails")] [Authorize] // 仅允许已认证用户访问 public async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log) { try { // 触发OBO流程,获取访问Graph的令牌 var scopes = new[] { "User.Read" }; await _tokenAcquisition.GetAccessTokenForUserAsync(scopes); // 调用Graph API,指定需要获取的用户属性(如职位、部门等) var userProfile = await _graphServiceClient.Me .Request() .Select(u => new { u.Id, u.DisplayName, u.Mail, u.JobTitle, u.Department, u.OfficeLocation }) .GetAsync(); return new OkObjectResult(userProfile); } catch (System.Exception ex) { log.LogError(ex, "获取用户扩展属性失败"); return new StatusCodeResult(StatusCodes.Status500InternalServerError); } } } }
4. 配置应用设置
在local.settings.json(本地开发)或Azure门户的函数应用设置中,添加Azure AD和Graph相关配置:
{ "Values": { "AzureWebJobsStorage": "UseDevelopmentStorage=true", "FUNCTIONS_WORKER_RUNTIME": "dotnet", "AzureAd:Instance": "https://login.microsoftonline.com/", "AzureAd:TenantId": "<你的Entra ID租户ID>", "AzureAd:ClientId": "<Azure函数的客户端ID>", "AzureAd:ClientSecret": "<Azure函数的客户端密钥(系统分配身份可省略)>", "GraphApiUrl": "https://graph.microsoft.com/v1.0" } }
二、前端调用方式
前端直接调用上述Azure函数的端点(如/api/FetchUserDetails),即可获取包含职位等属性的用户信息。示例代码(JavaScript):
async function getUserProfile() { try { const response = await fetch('/api/FetchUserDetails', { method: 'GET', credentials: 'include' // 携带认证Cookie }); const userData = await response.json(); console.log('用户职位:', userData.jobTitle); // 将属性渲染到页面对应位置 } catch (error) { console.error('获取用户信息失败:', error); } }
关键说明
- OBO流程会自动使用前端传递到后端的用户身份令牌,换取访问Microsoft Graph的权限令牌,无需前端处理令牌。
- 若需获取更多用户属性,可在Graph API的
Select方法中添加对应的字段(如u.MobilePhone、u.City等)。
内容的提问来源于stack exchange,提问作者Marc
相关产品推荐
相关产品推荐

