c# - 登录后无法使用身份验证令牌调用 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();
}
};
}));
解决方案
推荐阅读
- ios - 如何使用 NSLayoutConstraint 以编程方式在容器中居中表格页脚视图?
- javascript - 将行项目从一个表移动到另一个表,并在将选定行项目添加到第二个表之前验证在第一个表中输入的数据
- c# - c#语言的功率限制是多少
- java - 使用与我的本地主机相同的配置运行 dropwizard,在 vps 上出现错误
- python-3.x - 老板大战迷你游戏。如何让boss血量一直降到0
- r - 如何将矩阵中的特定字符数存储到R中的另一个向量中
- android - 如何增加 Vector Drawable 的大小?
- php - 如何在php中正确转义电子邮件标头
- speech-recognition - Kaldi:qsub 的输出是:qsub:在尝试运行 Common Voice 配方时非法 -c 值“”
- python-3.x - 我尝试使用 chromedriver 或 geckodriver 在 python 上打开 chrome 或 firefox,但打开了任何页面