I am trying to access the Microsoft Graph API to obtain a user’s outlook groups.
Here is the code to retrieve the access token:
public static async Task<string> GetGraphAccessTokenAsync()
{
string AzureAdGraphResourceURL = "https://graph.microsoft.com/";
string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey);
var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
AuthenticationContext authContext = new AuthenticationContext(
SettingsHelper.Authority, new ADALTokenCache(signedInUserUniqueName));
var result = await authContext.AcquireTokenSilentAsync(AzureAdGraphResourceURL, clientCredential, userIdentifier);
return result.AccessToken;
}
The method uses a settings helper as follows:
public class SettingsHelper
{
private static string _clientId = ConfigurationManager.AppSettings["ida:ClientID"];
private static string _appKey = ConfigurationManager.AppSettings["ida:Password"];
private static string _tenantId = ConfigurationManager.AppSettings["ida:TenantID"];
private static string _authorizationUri = "https://login.windows.net";
private static string _authority = "https://login.windows.net/{0}/";
private static string _graphResourceId = "https://graph.windows.net";
public static string ClientId
{
get
{
return _clientId;
}
}
public static string AppKey
{
get
{
return _appKey;
}
}
public static string TenantId
{
get
{
return _tenantId;
}
}
public static string AuthorizationUri
{
get
{
return _authorizationUri;
}
}
public static string Authority
{
get
{
return String.Format(_authority, _tenantId);
}
}
public static string AADGraphResourceId
{
get
{
return _graphResourceId;
}
}
}
This is the error that I get: Failed to acquire token silently. Call method AcquireToken
Exception Details:
Microsoft.IdentityModel.Clients.ActiveDirectory.AdalSilentTokenAcquisitionException : Failed to acquire token silently. Call method AcquireToken
The error occurs specifically at this line:
var result = await authContext.AcquireTokenSilentAsync(AzureAdGraphResourceURL, clientCredential, userIdentifier);
I have checked to ensure that the UserIdentifier matches the value in the cache, but it stills seems to reject the token. Any ideas of where I might be going wrong?