Microsoft Graph MVC如何强制重新身份验证



我需要在MVC核心应用程序中强制重新验证Microsoft Graph。

Graph对象是在ConfigureServices中使用以下代码段获得的:

var tokenAcquisition = context.HttpContext.RequestServices
.GetRequiredService<ITokenAcquisition>();
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(async (request) => {
var token = await tokenAcquisition
.GetAccessTokenForUserAsync(_scopes, user: context.Principal);
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
})
);

问题是令牌已过时,稍后对Graph的调用失败。很容易陷阱并放入一些重新验证代码,但它也会失败;MsalUiRequiredException:没有向AcquireTokenSilent调用传递帐户或登录提示";错误网上有很多关于这种情况的参考,但我找不到确切的回应。

控制器中的重新验证代码为:

if (ex.InnerException.InnerException is MsalUiRequiredException)
{
string[] _scopes = _config.GetValue<string>("AzureAd:GraphScopes")?.Split(' ');
var tokenAcquisition = _http.RequestServices.GetRequiredService<ITokenAcquisition>();
_graph = new GraphServiceClient(
new DelegateAuthenticationProvider(async (request) => 
{
var options = new TokenAcquisitionOptions() { ForceRefresh = true };
var token = await tokenAcquisition.GetAccessTokenForUserAsync(_scopes, user: User, tokenAcquisitionOptions: options);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
})
);
}

问题是如何成功地强制重新验证并获得新的Graph客户端?

回答我自己的问题时,发现它在控制器中很容易处理:

try
{
string token = await _tokenAcquisition
.GetAccessTokenForUserAsync(GraphConstants.Scopes);
return View().WithInfo("Token acquired", token);
}
catch (MicrosoftIdentityWebChallengeUserException)
{
return Challenge();
}

此代码段来自https://learn.microsoft.com/en-us/graph/tutorials/aspnet-core?tutorial-步骤=3

我假设您的应用程序正在强制用户登录,并且您正在使用该标识基于上下文的使用来获取Graph令牌。委托人:

.GetAccessTokenForUserAsync(_scopes, user: context.Principal);

当令牌到期时,我假设用于进入的原始令牌也在同一时间到期。这意味着没有用户,因此调用失败,并出现您所描述的错误。这让我觉得,在尝试获取新的图形令牌之前,您需要重新进行身份验证。

但是,您应该监视令牌,并在它过期之前获得一个新的令牌——静默地使用刷新令牌,而不是新的身份验证。

https://learn.microsoft.com/en-us/advertising/guides/authentication-oauth-get-tokens?view=bingads-13#刷新accesstoken

最新更新