【发布时间】:2021-03-15 01:18:53
【问题描述】:
我在尝试获取另一个应用程序的令牌时开始收到此错误。
其他信息:AADSTS70002:验证凭据时出错。 AADSTS50013:断言不在其有效时间范围内。
这在我从 AspNetCore 的 1.0.1 升级到 1.1.0 后开始发生。如果我清除我的 cookie,则此错误会消失一段时间。
以下是我用来获取此令牌的代码。它主要改编自 GitHub 上示例中的代码。
var userObjectId = (user.FindFirst(AuthSettings.UserObjectIdClaimName))?.Value;
AuthenticationResult authResult = null;
var authContext = GetAuthContext(userObjectId);
ClientCredential credential = new ClientCredential(AuthSettings.ClientId, AuthSettings.ClientSecret);
var claimsIdentity = user.Identity as ClaimsIdentity;
var token = claimsIdentity?.BootstrapContext as string;
if (token != null)
{
try
{
authResult = await authContext.AcquireTokenAsync(appId, credential,
new UserAssertion(token)); // Error here
}
catch (Exception) { }
}
if (authResult == null)
{
// Error no token in cache here
authResult = await authContext.AcquireTokenSilentAsync(appId, credential,
new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
}
return authResult.AccessToken;
你知道有趣的是AcquireTokenSilentAsync 在第一次尝试失败时发生的永远不会起作用,因为令牌缓存是空的。在我的 Startup 中,我在 OnAuthorizationCodeReceived 中有代码,该代码继续并将令牌存储在令牌缓存中。此回调从不执行。大概如果第一批代码不起作用,那么如果此代码起作用,则回退将处理它。
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
ClientId = authSettings.ClientId,
Authority = authSettings.Authority,
ResponseType = OpenIdConnectResponseType.IdToken,
PostLogoutRedirectUri = authSettings.PostLogoutUrl,
TokenValidationParameters = new TokenValidationParameters()
{
SaveSigninToken = true
},
Events = new OpenIdConnectEvents
{
OnRemoteFailure = authHelper.CreateOnRemoteFailureRedirectHandler("/Home/Error"),
OnAuthorizationCodeReceived =
authHelper.CreateOnAuthorizationCodeRecievedAcquireAdditionalTokenHandler(new[] { CustomerManagerApi })
},
});
这是当前没有为OnAuthorizationCodeRecieved 执行的代码:
var userObjectId = (context.Ticket?.Principal?.FindFirst(AuthSettings.UserObjectIdClaimName))?.Value;
var clientCred = new ClientCredential(AuthSettings.ClientId, AuthSettings.ClientSecret);
var authContext = new AuthenticationContext(AuthSettings.Authority, TokenCacheCreator(userObjectId));
var redirectAddressForAuthCode = new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]);
authContext.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code, redirectAddressForAuthCode, clientCred, applicationId);
context.HandleCodeRedemption();
【问题讨论】:
标签: asp.net-core openid-connect adal