Microsoft Graph - Failed to acquire token silently

Viewed 590

I am attempting to get data from the Microsoft graph in my web app.

When I call AcquireTokenSilentAsync() I get the error "Failed to acquire token silently. Call method AcquireToken".

Therefore I then tried using the AcquireTokenAsync() method. This obtains a token however, when I attempt to access the resource, I get 403 - Forbidden.

I have tested it in Fiddler and it works.

When I examine the token from AcquireTokenAsync() and compare it to the token obtained from fiddler, it is about 1/3 the length. I do not know if this is an issue and if there is a fix?

Does anybody know of a solution to this issue?

My code is as follows:

GetToken():

public async static Task<AuthenticationResult> GetTokenAsync(AuthenticationContext ctx, string resourceId)
{
    ClientCredential credential = new ClientCredential(OfficeSettings.ClientId, OfficeSettings.ClientSecret);
    var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
    UserIdentifier ident = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

    var redirectUrl = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

    try
    {
        var result = await ctx.AcquireTokenSilentAsync(resourceId, credential, ident);
        //var result = await ctx.AcquireTokenAsync(resourceId, credential);
        LastAuthority = ctx.Authority;
        return result;
    }
    catch (AdalException e)
    {
        ctx.TokenCache.Clear();
        return null;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

GetUserEmail() (Accessing resource):

private const string _allUsersUrl = "https://graph.microsoft.com/beta/users?$filter=displayName%20eq%20'{0}'";

public static async Task<List<string>> GetUserEmails(List<string> displayNames)
{
    var emails = new List<string>();
    using (var client = new HttpClient())
    {
        foreach (var name in displayNames)
        {
            var url = string.Format(_allUsersUrl, name.Replace(" ", "+")).Replace(" ", "%20");
            using (var req = new HttpRequestMessage(HttpMethod.Get, url))
            {
                var token = await GetToken();
                req.Headers.Add("Authorization", string.Format("Bearer {0}", token));
                req.Headers.TryAddWithoutValidation("Content-Type", "application/json");
                using (var response = await client.SendAsync(req))
                {
                    //TODO: Forbidden error message. However, token seems to be retrieved correctly
                    var content = await response.Content.ReadAsStringAsync();
                    foreach (var item in JObject.Parse(content)["value"])
                    {
                        emails.Add(item["userPrincipalName"].ToString());
                    }
                }
            }
        }
    }
    return emails;
}

EDIT:

I have also inspected the contents of the cache and compared this to the parameters being passed to AcquireTokenSilentAsync() and everything appears to match up.

1 Answers
Related