I want to get access token to use it to fetch email from outlook using microsoft graph api. My application will be Console based c# application which will run automatically after every 20 min and will fetch the email.
I am new to c# as well as microsoft graph, this is my first task related to these technology.
Problem is:
When i tried to fetch token using client_Credentials i was successfully able to do so, but now that token is expired i want to get new token and if I try to generate new token it is returning the expired one only.
Relevant code:
result = await context.AcquireTokenAsync(resourceUri, clientCredential);
Using AcquireTokenSilentAsync method return as error: "Failed to acquire token silently as no token was found in the cache. Call method AcquireToken."
Relevant code:
result = await authContext.AcquireTokenSilentAsync(resourceUri, clientId);
My questions:
Is accessing token using client credential is correct way to fulfill my need?
I have read that using client_Credentials we do not need refresh_token, every time we try to connect we will get new token.
How to get new token every time I want to connect?
Any extra suggestion about how to approach to my main objective which are not asked in question would be dearly welcomed.
I'm attaching my code sample:
static async Task getAccessToken()
{
authContext = new AuthenticationContext("https://login.microsoftonline.com/<tenantId>");
try
{
result = await authContext.AcquireTokenSilentAsync(resourceUri, clientId);
}
catch (Exception ex)
{
Console.WriteLine(ex);
try
{
result = await authContext.AcquireTokenAsync(resourceUri, clientCredential);
Console.WriteLine("" + result.AccessToken+"\n\n");
}
catch (Exception e)
{
Console.WriteLine("\n AcquireTokenAsync failed\n");
Console.WriteLine(""+e);
}
}
if (result == null)
{
Console.WriteLine("Canceling attempt to get access token.\n");
return;
}
Console.WriteLine(result.AccessToken);
}