web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Small and medium business | Business Central, N...
Suggested Answer

Unauthorised 401 Error Occurs Rest API in business Central

(0) ShareShare
ReportReport
Posted on by 99

Access Token generated successfuly....but Show error 401 Unauthorized.

pastedimage1658398391730v1.png

 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;

I have the same question (0)
  • Suggested answer
    Chameera Kavinda Profile Picture
    510 on at

    Hi Sejal,

    Did you create an AAD Application in BC using the ClientId with the required permissions?

    Please go through the below documentation for better understanding.

    https://yzhums.com/20690/

    It's recommended to check your API using POSTMAN or any other application and verify all the thing are in line.

    Thank you.

  • Suggested answer
    divyeshchitte Profile Picture
    968 on at

    Can you use the URL in POST MAN ?

    Have you passed correct Headers in the API?

    Can you share a screen shot for which this API is working

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Small and medium business | Business Central, NAV, RMS

#1
OussamaSabbouh Profile Picture

OussamaSabbouh 2,238

#2
YUN ZHU Profile Picture

YUN ZHU 773 Super User 2025 Season 2

#3
Sumit Singh Profile Picture

Sumit Singh 630

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans