c# - 处理 AcquireTokenOnBehalfOf 请求中的 MsalUiRequiredException
问题描述
我正在尝试使用 MSAL 通过 3 个服务链接身份验证。ClaimsIdentity
验证令牌后,我将使用其他声明填充。用户使用 ServiceA 范围进行身份验证。ServiceA 然后使用 AcquireTokenOnBehalfOf 调用 ServiceB。ServiceB 然后使用 AcquireTokenOnBehalfOf 调用 Microsoft Graph API。
如果用户同意 ServiceA 和 ServiceB,这将非常有用。但是,如果用户没有同意 ServiceB,MsalUiRequiredException
则抛出。
我可以通过使用 Azure 门户中的“授权客户端应用程序”来避免 ServiceA 对 ServiceB 的同意。但是,我无法在 Microsoft Graph API 上使用该功能。我也没有使用管理员同意的选项。
我应该如何让 ServiceA 知道用户没有同意 ServiceB?该令牌已针对 ServiceA 进行了验证,因此我不确定我什至会做什么。我不能在一个请求中包含来自两个不同权限的范围。我是否发送两个身份验证请求而不使用 AcquireTokenOnBehalfOf?
这是我用于使用 Microsoft.Identity.Client 进行身份验证的代码。
public async Task PopulateClaimsAsync(ClaimsIdentity identity, JwtSecurityToken token, string redirectUrl)
{
try
{
var userAssertion = new UserAssertion(token.RawData, _jwtAssertionType);
var app = ConfidentialClientApplicationBuilder.Create(_authentationOptions.ClientId)
.WithAuthority(_authentationOptions.Authority)
.WithRedirectUri(redirectUrl)
.WithClientSecret(_authentationOptions.ClientSecret)
.Build();
app.AppTokenCache.SetBeforeAccess(OnBeforeAccess);
app.AppTokenCache.SetAfterAccess(OnAfterAccess);
var result = await app.AcquireTokenOnBehalfOf(new string[] { "User.Read" }, userAssertion).ExecuteAsync();
var graphToken = result.AccessToken;
var me = await _graphApiClient.GetMe(graphToken);
//snip
}
catch (MsalUiRequiredException ex)
{
//Microsoft.Identity.Client.MsalUiRequiredException: AADSTS65001: The user or administrator has not consented to use the application with ID
//??
}
}