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

如何在应用权限场景下通过依赖注入使用GraphServiceClient

问题描述

我已经手动实现了一个获取Azure访问令牌的接口和类,代码如下:

using ARMS_API.CloudStorage;
using Azure.Identity;
using Box.V2.Config;
using Box.V2.JWTAuth;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.Graph;
using Microsoft.Graph.Drives.Item.Items.Item.CreateUploadSession;
using Microsoft.Graph.Models;

namespace ARMS_API.Azure
{
    public class AzureServices : IAzureServices
    {
        protected IConfiguration _configuration;
        public AzureServices(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public GraphServiceClient GetGraphClient()
        {
            string[] scopes = new[] { "https://graph.microsoft.com/.default" };
            var chainedTokenCredential = GetChainedTokenCredentials();
            return new GraphServiceClient(chainedTokenCredential, scopes);
        }

        private ChainedTokenCredential GetChainedTokenCredentials()
        {
            var tenantId = _configuration["AzureAd:TenantId"]!;
            var clientId = _configuration["AzureAd:ClientId"]!;
            var clientSecret = _configuration["AzureAd:ClientSecret"]!;

            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            var devClientSecretCredential = new ClientSecretCredential(
                tenantId, clientId, clientSecret, options);

            var chainedTokenCredential = new ChainedTokenCredential(devClientSecretCredential);
            return chainedTokenCredential;
        }
    }
}

我希望像委托权限场景那样,直接在Program.cs中配置服务,实现GraphServiceClient的依赖注入,无需手动创建。我尝试了应用权限场景的配置:

builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration, "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes: new string[] { "https://graph.microsoft.com/.default" })
.AddDistributedTokenCaches();

但找不到委托权限场景中EnableTokenAcquisitionToCallDownstreamApi()后可以附加的.AddMicrosoftGraph()方法,请问我遗漏了什么步骤?


解决方案

你的核心问题是用错了场景对应的配置方法:AddMicrosoftIdentityWebAppAuthentication是用户登录的委托权限场景(代表用户调用Graph)的配置,而你需要的是应用权限场景(服务自身调用Graph,无用户上下文)的配置,两者的扩展方法不同。

步骤1:安装必要的NuGet包

确保项目已安装以下包:

  • Microsoft.Identity.Web.GraphServiceClient:提供GraphServiceClient的DI扩展
  • Azure.Identity:提供客户端凭证相关的实现

步骤2:在Program.cs中配置应用权限的GraphServiceClient

有两种简洁的配置方式:

方式一:直接注册GraphServiceClient(手动构建凭证)

builder.Services.AddSingleton<GraphServiceClient>(serviceProvider =>
{
    var config = serviceProvider.GetRequiredService<IConfiguration>();
    
    var tenantId = config["AzureAd:TenantId"]!;
    var clientId = config["AzureAd:ClientId"]!;
    var clientSecret = config["AzureAd:ClientSecret"]!;

    var credentialOptions = new TokenCredentialOptions
    {
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
    };

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

    return new GraphServiceClient(clientSecretCredential, scopes);
});

方式二:用Microsoft Identity Web的应用权限扩展方法

使用专门的扩展方法简化配置:

builder.Services.AddMicrosoftGraphForAppOnlyAuth(
    configuration: builder.Configuration,
    configSectionName: "AzureAd",
    initialScopes: new[] { "https://graph.microsoft.com/.default" });

或者更灵活的链式配置:

builder.Services.AddMicrosoftGraph()
    .AddClientSecretCredential(options =>
    {
        builder.Configuration.Bind("AzureAd", options);
    })
    .AddScopes("https://graph.microsoft.com/.default");

步骤3:直接注入使用

配置完成后,就可以在需要的类中直接注入GraphServiceClient,无需手动创建:

public class YourService
{
    private readonly GraphServiceClient _graphClient;

    public YourService(GraphServiceClient graphClient)
    {
        _graphClient = graphClient;
    }

    // 使用_graphClient调用Graph API
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 15:45:57