【问题标题】:AdalSilentTokenAcquisitionException when trying to acquire the token in c#尝试在 c# 中获取令牌时出现 AdalSilentTokenAcquisitionException
【发布时间】:2021-06-07 05:26:06
【问题描述】:

我正在尝试使用 acquireTokenSilentAsync 连接到我的 azure 应用程序,但出现异常,这是代码:

public class Oauth
    {
        public const string OAuthHeader = "Authorization";
        public static  String GetUserAccessTokenAsync()
        {
            AuthenticationResult result = null;
            string aadTenant = TestConfiguration.Default.ActiveDirectoryTenant;
            string aadClientAppId = TestConfiguration.Default.ActiveDirectoryClientAppId;
            string aadResource = TestConfiguration.Default.ActiveDirectoryResource;

            var authenticationContext = new AuthenticationContext(aadTenant, TokenCache.DefaultShared);

            result = authenticationContext.AcquireTokenSilentAsync(aadResource, aadClientAppId).Result;

            if (result != null)
            {
                var accessToken = result.AccessToken;
                // Use the token
                return accessToken;
            }
            else
            {
                return "";
            }
        }
    }

我在下面这一行收到此错误:

result = authenticationContext.AcquireTokenSilentAsync(aadResource, aadClientAppId).Result;

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

怎么了?

【问题讨论】:

    标签: c# azure-active-directory


    【解决方案1】:

    当你尝试静默获取token时,它会从TokenCache中获取token或者静默使用refreshToken。因此,当缓存中没有令牌时,AdalException 返回。你可以参考这个article

    注意AcquireTokenSilent不需要在Client中调用 凭证流(当应用程序在没有用户的情况下获取令牌时, 但以自己的名义)

    请注意 AcquireTokenSilent 可能因多种原因而失败,例如 缓存不包含用户的令牌,或令牌已过期 并且无法刷新。

    try
    {
        result = await ac.AcquireTokenSilentAsync(resource, clientId);
    }
    catch (AdalException adalException)
    {
        if (adalException.ErrorCode == AdalError.FailedToAcquireTokenSilently
            || adalException.ErrorCode == AdalError.InteractionRequired)
        {
            result = await ac.AcquireTokenAsync(resource, clientId, redirectUri,
                                           new PlatformParameters(PromptBehavior.Auto));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-13
      • 2022-06-23
      • 2011-10-25
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多