编程语言
首页 > 编程语言> > C#-Azure-AD-AcquireTokenSilent提供错误failed_to_acquire_token_silently

C#-Azure-AD-AcquireTokenSilent提供错误failed_to_acquire_token_silently

作者:互联网

我们正在使用Azure AD每30分钟进行身份验证并获取刷新的访问令牌.我们调用以下获取安全令牌并将其添加到请求标头的方法.

var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
var authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId));
var credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientId"],
ConfigurationManager.AppSettings["ida:ClientSecret"]);

    try
    {
    var authenticationResult = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["WebAPIBaseAddress"], credential, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
    //set cookie for azure oauth refresh token - on successful login
    var httpCookie = HttpContext.Current.Response.Cookies["RefreshToken"];
    if (httpCookie != null)
        httpCookie.Value = authenticationResult.RefreshToken;

    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
    }
    catch
    {
    //Get access token using Refresh Token 
    var authenticationResult = authContext.AcquireTokenByRefreshToken(httpCookie.Value, credential, ConfigurationManager.AppSettings["WebAPIBaseAddress"]);
    }

在上述方法中,我们使用了AcquireTokenSilent方法,该方法为我们提供了访问令牌.由于访问令牌仅持续特定时间段.
到期后,我们调用AcquireTokenByRefreshToken以获取刷新令牌.

上面的代码运行良好,但是我们随机得到以下异常:

Microsoft.IdentityModel.Clients.ActiveDirectory.AdalSilentTokenAcquisitionException: Failed to acquire token silently. Call method AcquireToken 
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenSilentHandler.SendTokenRequestAsync() 
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<RunAsync>d__0.MoveNext()
ErrorCode: failed_to_acquire_token_silently

这种不一致的行为可能是什么原因?相同的代码在少数环境(Stage / Dev)上运行,但是在生产环境中随机抛出错误.

请提出建议.

解决方法:

我们能够解决这个问题.代码本身似乎是一个小错误.
当AccessToken过期时,它将引发异常,并尝试使用catch块中的AcquireTokenByRefreshToken来获取一个新的异常.在这里,我们没有在Cookie中重新设置新收到的刷新令牌.
我们还需要在catch块中添加以下语句,以便它将获得Refresh令牌,然后可以将其传递回以生成新的Access Token.

httpCookie.Value = authenticationResult.RefreshToken;

标签:adal,azure,azure-active-directory,c
来源: https://codeday.me/bug/20191119/2033868.html