You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Microsoft.Graph获取用户AccountEnabled布尔值而非NULL及权限?

使用Microsoft Graph库获取用户AccountEnabled属性完整指南

一、所需Entra ID应用权限

要获取用户的AccountEnabled属性,需配置以下应用权限(后台服务场景优先选择,委派权限仅适用于用户登录交互场景):

  • User.Read.All:允许读取所有用户的完整属性(包含AccountEnabled)
  • Directory.Read.All:更高权限,可读取目录内所有对象属性(包含用户状态)

注意:上述权限均需要全局管理员或用户管理员授予管理员同意,仅添加权限未同意会导致返回数据不完整或权限不足。

二、代码修正(核心问题:默认返回属性集不含AccountEnabled)

Microsoft Graph API默认仅返回用户基础属性集,AccountEnabled不在默认返回列表中,必须显式指定要获取的属性才能拿到该字段值。修正后的代码如下:

public async Task<List<User>> GetUserList()
{
    // 显式指定需返回的属性,包含accountEnabled
    UserCollectionResponse userCollectionResponse = await GraphClient.Users
        .GetAsync(requestConfiguration =>
        {
            // 可按需添加其他需要的属性,如displayName、userPrincipalName等
            requestConfiguration.QueryParameters.Select = new string[] { "id", "accountEnabled", "displayName" };
        });

    List<User> userList = new List<User>();

    PageIterator<User, UserCollectionResponse> pageIterator =
        PageIterator<User, UserCollectionResponse>.CreatePageIterator(
            GraphClient, userCollectionResponse,
            user => { userList.Add(user); return true; });

    await pageIterator.IterateAsync();

    return userList;
}

关键说明:

  • 使用Select方法指定返回字段,accountEnabled是Graph API中该属性的标准驼峰命名(注意大小写)
  • 分页迭代逻辑无需修改,PageIterator会自动沿用请求配置获取后续页数据
  • 若需验证单个用户数据,可先测试单用户查询:
    var user = await GraphClient.Users["{user-id}"].GetAsync(requestConfiguration =>
    {
        requestConfiguration.QueryParameters.Select = new string[] { "accountEnabled" };
    });
    Console.WriteLine(user.AccountEnabled); // 应返回true/false而非null
    

三、验证步骤

  1. 确认权限状态:进入Entra ID控制台→应用注册→目标应用→权限,确认权限已显示“已授予管理员同意”
  2. 检查认证方式:确保Graph Client使用应用权限认证流程(如Client Credentials),而非委派权限流程
  3. 测试返回结果:调试代码查看user.AccountEnabled字段,确认已返回正确的布尔值

内容的提问来源于stack exchange,提问作者Lars Moe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 03:05:08