【问题标题】:Failed to acquire token silently - Microsoft Graph API无法以静默方式获取令牌 - Microsoft Graph API
【发布时间】:2017-10-08 16:54:57
【问题描述】:

我们正在使用 Microsoft Graph API 开发一个 ASP.NET MVC 项目。它很大程度上基于https://github.com/microsoftgraph/aspnet-snippets-sample 的示例代码。该应用程序起初运行良好——我们可以使用我们的租户帐户登录并从图表中获取数据。但是,如果我们从 Visual Studio 开始一个新会话,或者我们只是稍等片刻,AcquireTokenSilentAsync 会抛出

静默获取令牌失败

如果网络浏览器缓存被清除,它会再次工作,但过一段时间又会出现错误。 我们已尝试将权限更改为公共、组织和租户,但错误仍然存​​在。

我们获取访问令牌的方法如下:

 // Gets an access token and its expiration date. First tries to get the token from the token cache.
    public async Task<string> GetUserAccessTokenAsync()
    {
        // Initialize the cache.
        HttpContextBase context = HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase;

        tokenCache = new SessionTokenCache(
            ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value,
            context);
        IEnumerable<TokenCacheItem> cachedItems = tokenCache.ReadItems(appId); // see what's in the cache
        if (cachedItems.Count() > 0)
            return cachedItems.First().Token;

        if (!redirectUri.EndsWith("/")) redirectUri = redirectUri + "/";
        string[] segments = context.Request.Path.Split(new char[] { '/' });
        ConfidentialClientApplication cca = new ConfidentialClientApplication(
            appId,
            redirectUri + segments[1],
            new ClientCredential(appSecret),
            tokenCache);

        string allScopes = nonAdminScopes;
        string[] scopes = allScopes.Split(new char[] { ' ' });
        try
        {
            AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes);
            return result.Token;
        }

        // Unable to retrieve the access token silently.
        catch (MsalSilentTokenAcquisitionException)
        {
            HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
              new AuthenticationProperties() { RedirectUri = redirectUri + segments[1] },
              OpenIdConnectAuthenticationDefaults.AuthenticationType);

            throw new ServiceException(
                new Error
                {
                    Code = GraphErrorCode.AuthenticationFailure.ToString(),
                    Message = Resource.Error_AuthChallengeNeeded,
                });
        }
    }

任何想法为什么无法静默获取令牌?

【问题讨论】:

    标签: c# asp.net-mvc token microsoft-graph-api


    【解决方案1】:

    你如何处理抛出的异常?在您提供的示例中,他们使用 try/catch 处理错误,如果引发异常并且错误消息匹配,他们将返回空结果。该请求随后会被 OpenId 中间件拦截(因为 ..GetOwinContext().Authentication.Challenge() 将响应代码设置为 401,身份验证类型设置为 OpenIdConnectAuthenticationDefaults.AuthenticationType)。

            try
            {
    
                // Initialize the GraphServiceClient.
                GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
    
                // Get the files and folders in the current user's drive.
                results.Items = await filesService.GetMyFilesAndFolders(graphClient);
            }
            catch (ServiceException se)
            {
                if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
                return RedirectToAction("Index", "Error", new { message = string.Format(Resource.Error_Message, Request.RawUrl, se.Error.Code, se.Error.Message) });
            }
    

    【讨论】:

      猜你喜欢
      • 2016-07-12
      • 2016-07-05
      • 2016-08-12
      • 2023-01-01
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      相关资源
      最近更新 更多