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

如何修改代码从Azure Active Directory获取仅活跃用户的指定信息?

从Azure Active Directory获取仅活跃用户指定信息的修改方案

核心修改方向

旧的本地Active Directory(AD)代码依赖LDAP协议和System.DirectoryServices类库,切换到Azure AD后,必须改用Microsoft Graph API实现需求,具体修改步骤如下:


1. 替换依赖库

卸载原本地AD相关的System.DirectoryServices类库,安装Microsoft Graph SDK相关NuGet包:

Install-Package Microsoft.Graph
Install-Package Microsoft.Identity.Client

2. 配置Azure AD应用权限

在Azure门户中注册一个应用程序,获取以下信息并配置权限:

  • 租户ID(Tenant ID)
  • 客户端ID(Client ID)
  • 客户端密钥(Client Secret)
  • 为应用添加User.Read.All应用权限(需管理员同意)

3. 编写获取活跃用户的代码

以下是完整C#示例,仅拉取accountEnabled为true的活跃用户,并提取所需字段:

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System.Collections.Generic;
using System.Threading.Tasks;

public class AzureADUserService
{
    private readonly GraphServiceClient _graphClient;

    public AzureADUserService(string tenantId, string clientId, string clientSecret)
    {
        var confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create(clientId)
            .WithTenantId(tenantId)
            .WithClientSecret(clientSecret)
            .Build();

        var authProvider = new ClientCredentialProvider(confidentialClientApplication);
        _graphClient = new GraphServiceClient(authProvider);
    }

    public async Task<List<UserInfo>> GetActiveUsersAsync()
    {
        var users = await _graphClient.Users
            .Request()
            .Filter("accountEnabled eq true") // 筛选仅活跃用户
            .Select("givenName,surname,mail,userPrincipalName") // 指定需要的字段
            .GetAsync();

        var userList = new List<UserInfo>();
        foreach (var user in users)
        {
            userList.Add(new UserInfo
            {
                FirstName = user.GivenName,
                LastName = user.Surname,
                Email = user.Mail,
                EnterpriseId = user.UserPrincipalName
            });
        }

        return userList;
    }
}

// 存储用户信息的实体类
public class UserInfo
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string EnterpriseId { get; set; }
}

4. 字段映射说明

需求字段Azure AD Graph API 对应字段
First NamegivenName
Last Namesurname
Emailmail(需用户邮箱已在Azure AD中配置)
Enterprise IDuserPrincipalName(通常为企业统一身份ID)

关键注意点

  • 确保应用权限已获得管理员同意,否则会出现权限不足的错误
  • 如果你的企业ID不是userPrincipalName,需确认Azure AD中对应的自定义属性字段,修改Select和映射逻辑即可
  • 处理大量用户时可添加分页逻辑(示例为基础版本,可通过Top()和Skip()方法实现分页)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:20:37