C# application (.Net framework 4.8) I'm working on is relying on files stored on OneDrive on technical user. Files are accessed via Microsoft Graph SDK. The authenthication is performed via Msal token stored on the machine. We've also implemented watcher service ensuring that the Token is refreshed before expiration.
Recently I've been assigned to migrate everything to different user, however I'm struggling to acquire Token for Authenthication with all of the properties I need.
The token which is currently in place and is used in the application have following structure:
{
"AccessToken": {
...
}
},
"RefreshToken": {
...
}
},
"IdToken": {
...
}
},
"Account": {
"": {
"home_account_id": "",
"environment": "",
"client_info": "",
"username": "",
"name": "",
"local_account_id": "",
"authority_type": "MSSTS",
"realm": ""
}
},
"AppMetadata": {
"appmetadata-login.windows.net-{appId}": {
"environment": "",
"client_id": ""
}
}
}
And when I try to acquire the token according to following documentation: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
{
"token_type": "Bearer",
"scope": "openid profile email https://graph.microsoft.com/Files.ReadWrite.All",
"expires_in": 3599,
"ext_expires_in": 3599,
"access_token": "",
"refresh_token": "",
"id_token": ""
}
I get the token without the "Account" object/property in the JSON. The question is, how can I obtain the access token including the account property?
After checking the access token via jwt.ms it turns out that the accounts property are embedded in the access token. When I try to access the account via following code it is not possible. Confidential client application with the new token does not contain any accounts.
private async Task<string> GetTokenAsync()
{
var cca = ConfidentialClientApplicationBuilder.Create(appId).WithClientSecret(appSecret).WithRedirectUri(redirectUri).Build();
GraphTokenCache.TokenFilePath = tokenFilePath;
GraphTokenCache.EnableSerialization(cca.UserTokenCache);
var accounts = await cca.GetAccountsAsync();
var account = accounts.First(); // <- Always returns 0
var result = cca.AcquireTokenSilent(new[] { "Files.ReadWrite.All" }, account).ExecuteAsync().Result;
return result.AccessToken;
}
public class GraphTokenCache
{
public static string TokenFilePath;
public static void EnableSerialization(ITokenCache cache)
{
cache.SetBeforeAccess(BeforeAccessNotification);
cache.SetAfterAccess(AfterAccessNotification);
}
static void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
if (System.IO.File.Exists(TokenFilePath))
{
var bytes = System.IO.File.ReadAllBytes(TokenFilePath);
args.TokenCache.DeserializeMsalV3(bytes);
}
}
static void AfterAccessNotification(TokenCacheNotificationArgs args)
{
if (args.HasStateChanged)
{
var bytes = args.TokenCache.SerializeMsalV3();
System.IO.File.WriteAllBytes(TokenFilePath, bytes);
}
}
}
question from:
https://stackoverflow.com/questions/65672046/microsoft-graph-token-lacks-account-property