I have a table in a database with emails and their refresh tokens of multiple Hotmail/Outlook.com accounts (nothing else).
I'm trying to create an Access Token using the Refresh Token but I can't find any code using Microsoft.Identity.Client or Microsoft.Graph libraries to perform that action.
Here is the partial code in a console application:
static void Main(string[] args)
{
/* other code */
string email, refreshToken; // obtained from database
TokenCache tokenCache = new TokenCache(); // how do i "fill" this object?
ConfidentialClientApplication cca = new ConfidentialClientApplication(
"appId",
"redirectUri",
new ClientCredential("appSecret"),
tokenCache,
null);
IAccount account = cca
.GetAccountsAsync()
.Result
.FirstOrDefault();
AuthenticationResult result = cca
.AcquireTokenSilentAsync(new string[] { "scopes" }, account)
.Result;
GraphServiceClient client = new GraphServiceClient("https://outlook.office.com/api/v2.0/",
new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", result.AccessToken);
return Task.FromResult(0);
}));
var msgs = client
.Me
.MailFolders
.Inbox
.Messages
.Request()
.Select(m => new { m.Subject, m.ReceivedDateTime, m.From })
.Top(10)
.GetAsync();
/* more stuff to do */
}
I have been able to do this using PHP but now I need it to do it in .net
UPDATE: I will show the complete code using the answer of Marc LaFleur
ConfidentialClientApplication cca = new ConfidentialClientApplication(
appId,
redirectUri,
new ClientCredential(appSecret),
new TokenCache(),
null);
AuthenticationResult result = (cca as IByRefreshToken).
AcquireTokenByRefreshTokenAsync(scopes, refreshToken).Result;
GraphServiceClient client = new GraphServiceClient(
"https://outlook.office.com/api/v2.0/",
new DelegateAuthenticationProvider((requestMessage) => {
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
return Task.FromResult(0);
}
));
var msgs = client.Me.MailFolders.Inbox.Messages.Request().
OrderBy("receivedDateTime DESC").
Select(m => new { m.Subject, m.ReceivedDateTime, m.From }).
Top(10).
GetAsync().Result;