Consuming The Business Central administration center API

I would like to use BC admin center APIs, but have problem with authorization. I set up Azure AD based authentication following  official docs, and successfully got access token. But when I called api eg GET /admin/v2.1/applications/environments, I got Unathorized exception
Here is my code:

public void BCRequest(string AadTenantId, string ClientId, string SecretKey)
{
 const string url = "https://api.businesscentral.dynamics.com/admin/v2.1/applications/environments";
 const string ServerAppIdUri = "api://" +ClientId;
 
 const string ClientRedirectUrl = "https://login.microsoftonline.com/common/oauth2/nativeclient";
 var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/" +AadTenantId, false);
 ClientCredential clientCredential = new ClientCredential(ClientId, SecretKey);
 var authenticationResult = authenticationContext.AcquireTokenAsync(ServerAppIdUri, clientCredential).Result;
 PlatformParameters(PromptBehavior.SelectAccount)).GetAwaiter().GetResult();
 var tokenHeader = authenticationResult.CreateAuthorizationHeader();
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 request.Headers.Add("Authorization", tokenHeader);
 
 // Throws error "The remote server returned an error: (401) Unauthorized."
 var response=request.GetResponse();
}

I can't figure out where the problem is.
Thanks
Related
Recommended