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
Parents
No Data
Reply
  • Hi Tomaz,
    I am having same issue while authenticating using Oauth2 to access business central web serivce. The access token generated successfully but I'm unbale to access BC web service due to invalid credentials, problem is that the access token generated from below code is rather shorter (1500) characters but from postman it is around (1700) characters. Can you help in some regard ?
    thanks

Children
No Data
Related
Recommended