Access Token generated successfuly....but Show error 401 Unauthorized.
var ClientIdTxt: Label 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; ClientSecretTxt: Label 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; AadTenantIdTxt: Label 'sandbox'; AuthorityTxt: Label 'https://login.microsoftonline.com/bbXXXXXX-XXXX-XXXX-XXXX-XXXXXX/oauth2/v2.0/token'; BCEnvironmentNameTxt: Label 'sandbox'; BCCompanyIdTxt: Label 'bbexxxxxx-xxxx-xxxx-xxxx-xxxxxxxx5'; // BCBaseUrlTxt: Label 'https://api.businesscentral.dynamics.com/v2.0/{BCEnvironmentName}/api/v2.0/companies({BCCompanyId})'; AccessToken: Text; AccesTokenExpires: DateTime; contentHeaders: HttpHeaders; request: HttpRequestMessage; HttpContent: HttpContent; trigger OnRun() var Customers: Text; Items: Text; begin Customers := CallBusinessCentralAPI(BCEnvironmentNameTxt, BCCompanyIdTxt, 'ExcelTemplateViewCompanyInformation'); // Items := CallBusinessCentralAPI(BCEnvironmentNameTxt, BCCompanyIdTxt, 'items'); Message(Customers); Message(Items); end; procedure CallBusinessCentralAPI(BCEnvironmentName: Text; BCCompanyId: Text; Resource: Text) Result: Text var Client: HttpClient; Response: HttpResponseMessage; Url: Text; response1: Text; begin Url := 'https://api.businesscentral.dynamics.com/v2.0/bbexxxxxx-xxxx-xxxx-xxxx-xxxxxxxx5/Cronus/ODataV4/Company(CRONUS IN)/ExcelTemplateViewCompanyInformation'; if (AccessToken = '') or (AccesTokenExpires = 0DT) or (AccesTokenExpires > CurrentDateTime) then GetAccessToken(AadTenantIdTxt); contentHeaders := Client.DefaultRequestHeaders(); contentHeaders.Add('Authorization', GetAuthenticationHeaderValue(AccessToken)); HttpContent.GetHeaders(contentHeaders); request.Content := HttpContent; request.SetRequestUri(Url); if not Client.Get(Url, Response) then begin if Response.IsBlockedByEnvironment then Error('Request was blocked by environment') else Error('Request to Business Central failed\%', GetLastErrorText()); end; if not Response.IsSuccessStatusCode then Error('Request to Business Central failed\%1 %2', Response.HttpStatusCode, Response.ReasonPhrase); Response.Content.ReadAs(Result); end; local procedure GetAccessToken(AadTenantId: Text) var OAuth2: Codeunit OAuth2; Scopes: List of [Text]; begin Scopes.Add('https://api.businesscentral.dynamics.com/.default'); if not OAuth2.AcquireTokenWithClientCredentials(ClientIdTxt, ClientSecretTxt, GetAuthorityUrl(AadTenantId), '', Scopes, AccessToken) then Error('Failed to retrieve access token\', GetLastErrorText()); AccesTokenExpires := CurrentDateTime (3599 * 1000); end; local procedure GetAuthenticationHeaderValue(AccessToken: Text) Value: Text; begin Value := StrSubstNo('Bearer %1', AccessToken); end; local procedure GetAuthorityUrl(AadTenantId: Text) Url: Text begin Url := AuthorityTxt; Url := Url.Replace('{AadTenantId}', AadTenantId); end;