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

.NET中如何通过注入的Graph客户端使用应用权限调用Microsoft Graph

用应用权限调用Microsoft Graph的实现方法

1. 配置应用权限认证参数

在appsettings.json中添加应用权限所需的认证配置:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "TenantId": "你的租户ID",
  "ClientId": "你的应用客户端ID",
  "ClientSecret": "你的应用客户端密钥",
  "GraphScopes": "https://graph.microsoft.com/.default"
}

如果使用证书认证,可替换ClientSecret为证书相关配置(如CertificateName)。

2. 注册应用权限专属Graph客户端

在Program.cs中,除默认的委托权限客户端外,单独注册一个用于应用权限的Graph服务:

builder.Services.AddAppPermissionGraphService(builder.Configuration);

// 扩展方法实现
public static IServiceCollection AddAppPermissionGraphService(this IServiceCollection services, IConfiguration config)
{
    var azureAdSection = config.GetSection("AzureAd");
    var scopes = new[] { azureAdSection["GraphScopes"] };

    var credential = new ClientSecretCredential(
        azureAdSection["TenantId"],
        azureAdSection["ClientId"],
        azureAdSection["ClientSecret"]);

    // 用键控注册区分两个客户端,避免和委托权限实例冲突
    services.AddKeyedSingleton<GraphServiceClient>("AppPermissionGraph", sp => 
        new GraphServiceClient(credential, scopes));

    return services;
}

3. 在业务方法中使用应用权限客户端

通过键控注入获取应用权限专属的Graph客户端,调用对应API:

private readonly GraphServiceClient _appGraphClient;

public YourBusinessService([FromKeyedServices("AppPermissionGraph")] GraphServiceClient appGraphClient)
{
    _appGraphClient = appGraphClient;
}

public async Task ExecuteAppPermissionOperation()
{
    // 示例:调用需要应用权限的接口,如获取所有租户用户
    var users = await _appGraphClient.Users.Request().GetAsync();
}

4. 确认Azure端权限配置

在Azure门户的应用注册页面:

  • 添加所需的应用权限(而非委托权限),比如User.Read.All、Group.ReadWrite.All等
  • 完成管理员同意操作,确保权限生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:55:15