'Error in SharePoint oAuth Authentication using Sharepoint Online CSOM and PnP in .net core

I am trying to make sharepoint authentication using oAuth(Azure AD App) using Sharepoint Online CSOM and PnP, but it gives error "The given key was not present in the dictionary.". I have created Azure AD App and added API permission for Sharepoint AllSite.FullControl in that app.

I am using trial sharepoint tenant.

Here is my code snippets:

ClientContext _sharepointContaxt = null;
string Username = [Username];
string Password = [Password];
string AppId="67b1845e-88b1-4e6c-b7db-7f1d3abe3b06";
Uri site = new Uri([Sharepoint_site_url]);                  
using (var authenticationManager = new AuthenticationManager("67b1845e-88b1-4e6c-b7db-7f1e3aae3a06"))
using (_sharepointContaxt = authenticationManager.GetContext(site, Username, SecurePassword(Password)))
{
   Web web = _sharepointContaxt.Web;
   _sharepointContaxt.Load(web);
   _sharepointContaxt.ExecuteQuery();
}


Solution 1:[1]

I faced the same "The given key was not present in the dictionary." issue whenever I occasionally sent Post request to Azure AD in a for loop. I'm not sure if this failure scenario is as the same as yours.

One of my debug way is to check the dictionary and see which "given key" was lost. In AuthenticationManager class, there is a private method called AcquireTokenAsync. This method is to request Azure AD to return SPO accessing token, and save it as a Json format in variable tokenResult, and then use GetProperty("access_token") to get token.

If Azure AD did not return SPO token for some reason, access_token might not be available in the tokenResult, result in the error code you saw.

In this case, error message in tokenResult help you to see the reason why Azure AD did not return the token.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Evan Hsiao