Skip to main content

Notifications

Small and medium business | Business Central, N...
Suggested answer

Unauthorised 401 Error Occurs Rest API in business Central

(0) ShareShare
ReportReport
Posted on by 95

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;

  • Suggested answer
    divyeshchitte Profile Picture
    divyeshchitte 950 on at
    RE: Unauthorised 401 Error Occurs Rest API in business Central

    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

  • Suggested answer
    Chameera Kavinda Profile Picture
    Chameera Kavinda 510 on at
    RE: Unauthorised 401 Error Occurs Rest API in business Central

    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.

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

News and Announcements

Announcing Category Subscriptions!

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Verified Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,359 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,370 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans