The problem was, that I was requesting a token for the second time (badly) after the first successful token instead of just reading it out from TokenCache.
The solution:
Getting token from authorization code at login and storing it in cache:
public async Task<AuthenticationResult> GetTokenByAuthorizationCodeAsync(string userId, string code)
{
TokenCache userTokenCache = new SessionTokenCache(userId, _memoryCache).GetCacheInstance();
try
{
AuthenticationContext authContext = new AuthenticationContext(_aadInstance, userTokenCache);
ClientCredential credential = new ClientCredential(_appId, _appSecret);
AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(_redirectUri), credential, _graphResourceId);
return result;
}
catch (Exception)
{
return null;
}
}
And when requesting a GraphServiceClient
I just read the correct token from cache:
public async Task<string> GetUserAccessTokenAsync(string userId)
{
TokenCache userTokenCache = new SessionTokenCache(userId, _memoryCache).GetCacheInstance();
try
{
AuthenticationContext authContext = new AuthenticationContext(_aadInstance, userTokenCache);
ClientCredential credential = new ClientCredential(_appId, _appSecret);
AuthenticationResult result = await authContext.AcquireTokenSilentAsync(_graphResourceId, credential, new UserIdentifier(userId, UserIdentifierType.UniqueId));
return result.AccessToken;
}
catch (Exception)
{
return null;
}
}