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

使用C#和Graph API从Azure AD获取用户详情及报错解决咨询

问题解决:通过UPN/Object ID获取Azure AD用户详情

错误原因分析

  1. 异步方法未正确等待:userDetail方法中调用GraphClient.Me.GetAsync()是异步操作,但未使用await关键字,导致user变量实际是Task<User>类型,直接打印会引发调试时的表达式计算错误。
  2. /me端点不适用当前认证方式:你使用的是ClientSecretCredential(应用权限认证),/me端点仅适用于用户身份认证(代表当前登录用户),应用权限模式下无法使用该端点,必须通过用户的UPN或Object ID调用/users/{id}接口。
  3. 缺少必要权限:确保你的Azure AD应用已添加User.Read.All(或更高权限)的应用权限,并完成管理员同意,否则会返回权限不足错误。

修正后的代码

using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;

namespace UserProperties;

public class GraphHandler
{
    public GraphServiceClient GraphClient { get; set; }

    public GraphHandler(string tenantId, string clientId, string clientSecret)
    {
        GraphClient = CreateGraphClient(tenantId, clientId, clientSecret);
    }

    public GraphServiceClient CreateGraphClient(string tenantId, string clientId, string clientSecret)
    {
        var options = new TokenCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud            
        };

        var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
        var scopes = new[] { "https://graph.microsoft.com/.default" };

        return new GraphServiceClient(clientSecretCredential, scopes);
    }

    // 通过UPN或Object ID获取用户详情
    public async Task<User?> GetUserByIdOrUpn(string identifier)
    {
        try
        {
            return await GraphClient.Users[identifier].GetAsync(requestConfiguration =>
            {
                // 可选:指定需要返回的用户属性,减少响应数据量
                requestConfiguration.QueryParameters.Select = new[] { "id", "userPrincipalName", "displayName", "mail", "jobTitle" };
            });
        }
        catch (ServiceException ex)
        {
            Console.WriteLine($"获取用户失败:{ex.Message}");
            return null;
        }
    }

    // 示例:异步获取并打印用户详情
    public async Task PrintUserDetail(string userIdOrUpn)
    {
        var user = await GetUserByIdOrUpn(userIdOrUpn);
        if (user != null)
        {
            Console.WriteLine($"用户ID: {user.Id}");
            Console.WriteLine($"UPN: {user.UserPrincipalName}");
            Console.WriteLine($"显示名称: {user.DisplayName}");
            Console.WriteLine($"邮箱: {user.Mail}");
            Console.WriteLine($"职位: {user.JobTitle}");
        }
        else
        {
            Console.WriteLine("未找到该用户");
        }
    }
}

使用示例

// 初始化GraphHandler
var graphHandler = new GraphHandler("你的租户ID", "你的客户端ID", "你的客户端密钥");
// 通过UPN获取用户详情
await graphHandler.PrintUserDetail("user@domain.com");
// 或通过Object ID获取
await graphHandler.PrintUserDetail("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");

额外注意事项

  • 确保Azure AD应用已配置应用权限:在Azure门户的应用注册中,添加User.Read.All权限并完成管理员同意。
  • 异步方法必须在async方法中调用,避免同步阻塞或未处理的Task导致的异常。
  • 可以通过Select参数指定需要的属性,提升接口调用效率,避免返回不必要的用户数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 07:17:10