在将Azure Active Directory dotnetcore Webapp实施到WebAPI OpenIDConnect时出错

时间:2018-10-03 07:26:40

标签: azure .net-core openid access-token

在将Azure活动目录dotnetcore webapp实施到webapi openidconnect时出现错误

ClientCredential credential = new ClientCredential(AzureAdOptions.Settings.ClientId, AzureAdOptions.Settings.ClientSecret);
string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
AuthenticationContext authContext = new AuthenticationContext(AzureAdOptions.Settings.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
AuthenticationResult result = await authContext.AcquireTokenSilentAsync(AzureAdOptions.Settings.TodoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

遇到错误

ErrorCode: failed_to_acquire_token_silently
Microsoft.IdentityModel.Clients.ActiveDirectory.AdalSilentTokenAcquisitionException: Failed to acquire token silently as no token was found in the cache. Call method AcquireToken

1 个答案:

答案 0 :(得分:0)

  

Microsoft.IdentityModel.Clients.ActiveDirectory.AdalSilentTokenAcquisitionException:无法静默获取令牌,因为在缓存中未找到令牌。调用方法AcquireToken

如果 no token is in the cache AcquireTokenSilentAsync将抛出AdalSilentTokenAcquisitionException,应用程序将需要调用AcquireTokenAsync

确保令牌高速缓存不在内存中,因此在进程重启时不会被擦除。 您可以做的另一件事是增加会话持续时间。默认情况下,ASP.NET将其限制为 20分钟,而默认情况下,OpenIdConnect遵循该限制。这意味着即使刷新令牌的使用时间更长,它也只会在20分钟后擦除这些令牌。

为此,您将需要像这样修改Startup.Auth.cs中的OpenIdConnect中间件注册:

app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                // ... Rest removed for brevity
                UseTokenLifetime = false
            });

然后在web.config中将会话时间设置为所需的时间:

<system.web>
  <sessionState timeout="720" /><!-- 12 hour session duration -->
</system.web>

有关更多详细信息,您可以参考此article