【发布时间】: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