0
votes

I have a working ASP.NET Core multi-tenant ADAL webapp. I'm working on integrating Microsoft Graph, but when I try to use a method on Microsoft.Graph.GraphServiceClient (eg. var me = await graphClient.Me.Request().GetAsync();), I get the error below:

Authorization_RequestDenied: Insufficient privileges to complete the operation.

I'm able to get correctly the Access Token. If I copy-paste the token from runtime to Postman, it is working correctly:

postman screenshot

But for the same token, it throws an error in ASP.NET core.

1
Are you sure the access token is being passed to the request? Can you use a tool like Fiddler to look at the network request and confirm?David

1 Answers

1
votes

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;
    }
}