首页 > 解决方案 > 登录后无法使用身份验证令牌调用 MS Graph

问题描述

我正在通过 Azure AD 使用 OpenIdConnect 登录 Azure Web 应用程序,并想调用 MSGraph 获取一些用户详细信息并将这些添加到自定义声明中。

身份验证正在工作,如果我将 GraphServiceClient 注入控制器,我可以从 MSGraph 中提取详细信息,但我希望能够在 Startup 中调用和设置自定义声明。

创建的 graphClient 调用不起作用,我没有收到错误。

不知道我哪里出错了。

这是我目前在 Startup.cs 中的 ConfigureServices 中所拥有的内容。

var initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');

       services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
            .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
                    .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
                    .AddInMemoryTokenCaches();
        services.AddScoped<ITokenCacheFactory, TokenCacheFactory>();

        services.Configure((Action<MicrosoftIdentityOptions>)(options =>
        {
            options.SaveTokens = true;
            options.Events = new OpenIdConnectEvents
            {
                OnTokenValidated = async ctx =>
                {
                    var options = new TokenCredentialOptions
                    {
                        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
                    };

                    var onBehalfOfFlowToken = ctx.SecurityToken.RawData;

                    var clientApp = ConfidentialClientApplicationBuilder
                        .Create(Configuration.GetSection("AzureAd:ClientId").Value)
                        .WithTenantId(Configuration.GetSection("AzureAd:TenantId").Value)
                        .WithClientSecret(Configuration.GetSection("AzureAd:ClientSecret").Value)
                        .Build();

                    var authProvider = new DelegateAuthenticationProvider(async (request) =>
                    {
                        var assertion = new UserAssertion(onBehalfOfFlowToken);
                        var result = await clientApp.AcquireTokenOnBehalfOf(initialScopes, assertion).ExecuteAsync();

                        request.Headers.Authorization =
                            new AuthenticationHeaderValue("Bearer", result.AccessToken);
                    });

                    var graphClient = new GraphServiceClient(authProvider);

                    var userDetail = await graphClient.Me.Request()
                            .Select(u => new
                            {
                                u.Mail,
                                u.UsageLocation,
                                u.OfficeLocation
                            })
                            .GetAsync();
                }
            };
        }));

标签: c#identitymsal

解决方案


推荐阅读