AcquireTokenSilentAsync无法正常运行

时间:2018-08-27 09:28:04

标签: access-token azure-ad-graph-api

我有以下设置:

var authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
string redirectUri = Url.Action("Authorize", "Planner", null, Request.Url.Scheme);

Uri authUri = authContext.GetAuthorizationRequestURL("https://graph.microsoft.com/", SettingsHelper.ClientId,
                                                      new Uri(redirectUri), UserIdentifier.AnyUser, null);
// Redirect the browser to the Azure signin page
return Redirect(authUri.ToString());

这将带您:

// Get the 'code' parameter from the Azure redirect
string authCode = Request.Params["code"];

// The same url we specified in the auth code request
string redirectUri = Url.Action("Authorize", "Planner", null, Request.Url.Scheme);

// Use client ID and secret to establish app identity
ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);

//FileTokenCache at specific location
TokenCache fileTokenCache = new FilesBasedAdalV3TokenCache("C:\\temp\\justin.bin");
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthorityTenantID, fileTokenCache);

AuthenticationResult authResult = null;
try
{
     // Get the token silently first
     authResult = await authContext.AcquireTokenSilentAsync(SettingsHelper.O365UnifiedResource, credential, UserIdentifier.AnyUser);   
}
catch (AdalException ex)
{
     authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, fileTokenCache);

     authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(authCode, new Uri(redirectUri), credential, SettingsHelper.O365UnifiedResource);

}

令牌已成功保存在文件中,并且似乎也已成功检索到该令牌。但是,静默令牌获取仍然给出使用非静默功能首先获取令牌的例外。我想念什么?

请注意,O365UnifiedResource设置为https://graph.microsoft.com/

1 个答案:

答案 0 :(得分:0)

通过使用

解决了这个问题
new UserIdentifier("<email address used to login microsoft apps>", UserIdentifierType.RequiredDisplayableId)

代替

UserIdentifier.AnyUser

并将客户ID固定为应用程序注册中指定的APP ID