I am trying to get data from a Microsoft chart in my web application.
When I call AcquireTokenSilentAsync(), I get the error message "Failed to get the token silently. AcquireToken call method."
So I tried to use the method AcquireTokenAsync(). However, this gets the token, when I try to access the resource, I get 403 - Forbidden.
I tested it in Fiddler and it works.
When I look at the token from AcquireTokenAsync()and compare it with the token received from the violinist, it is about 1/3 of the length. I do not know if this is a problem, and is there a fix?
Does anyone know a solution to this problem?
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);
LastAuthority = ctx.Authority;
return result;
}
catch (AdalException e)
{
ctx.TokenCache.Clear();
return null;
}
catch (Exception ex)
{
throw ex;
}
}
GetUserEmail () (access to the 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))
{
var content = await response.Content.ReadAsStringAsync();
foreach (var item in JObject.Parse(content)["value"])
{
emails.Add(item["userPrincipalName"].ToString());
}
}
}
}
}
return emails;
}
EDIT:
, AcquireTokenSilentAsync(), , .