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...
Answered

HttpClient with Authorization Issue

(1) ShareShare
ReportReport
Posted on by 289
So I have an AL codeunit procedure that obtains an access token from a third-party API service provider. The initial authorization isn't Basic or Bearer. It just requires the consumer the set an Authorization header value with the API key. If I make a test API request using Postman it works fine. From AL I'm getting an error stating.
 
The format of value '{myApiKey}' is invalid.
I redacted the {myApiKey} value, but it's a text value. A total of 108 characters. Below is my procedure. Specifically the procedure is failing at the Authorization header value being added. I have another procedure that makes an API call using an Authorization: Bearer {myAccessToken} header assignment, and that works fine. It must be something in BC 365 that doesn't like an Authorization header without the Basic or Bearer qualification. Any idea how I can resolve this issue?
 
procedure ObtainRestAccessToken(RequestUrl: Text; ApiKey: Text): Text
    var
        Client: HttpClient;
        RequestHeaders: HttpHeaders;
        RequestContent: HttpContent;
        ResponseMessage: HttpResponseMessage;
        RequestMessage: HttpRequestMessage;
        ResponseText: Text;
        ContentHeaders: HttpHeaders;
        JToken: JsonToken;
    begin
        RequestHeaders := Client.DefaultRequestHeaders();
        RequestHeaders.Add('Accept', 'application/json');
        RequestHeaders.Add('Authorization', ApiKey);
 
        RequestContent.GetHeaders(ContentHeaders);
        ContentHeaders.Clear();
        ContentHeaders.Add('Content-Type', 'application/json');
 
        Client.Post(RequestUrl, RequestContent, ResponseMessage);
        ResponseMessage.Content().ReadAs(ResponseText);
        JToken.ReadFrom('access_token');
        exit(GetValueAsText(JToken, ResponseText));
    end;
  • Greg Kujawa Profile Picture
    289 on at
    HttpClient with Authorization Issue
    RequestHeaderforToken.Add('api-key', Rec."api-key");
    @shrey chauhan, thanks for the reply. But this doesn't address the actual header that I specified was required. This header you suggested essentially is "api-key: {whateverApiKeyValue}" whereas the API service provider requires a header of "Authorization: {whateverApiKeyValue}." The solution was adding the header through TryAddWithoutValidation, since for some unknown reason the AL interpreter was rejecting the Authorization header not having a value with a leading Basic, Bearer, etc. qualifier.
  • Suggested answer
    Shrey Chauhan Profile Picture
    274 on at
    HttpClient with Authorization Issue
    Hello,

    You can also check this code if it's working for you
     
    procedure GetAuthorizationToken()
        begin
            Clear(JObject);
            Clear(JToken);
            Clear(JValue);
            Clear(PostmanAccessTokenValue);
            Clear(AuthTokenvalue);
            Clear(TokenExpiresValue);
            Clear(RequestMessageforToken);
            Clear(Content);
            Clear(RequestHeaderforToken);
            Clear(ContentHeaders);
            Clear(ResponseMessage);
            Clear(ResponseText);
            Content.GetHeaders(contentHeaders);
            RequestMessageforToken.GetHeaders(RequestHeaderforToken);
            RequestHeaderforToken.Add('api-key', Rec."api-key");
            RequestMessageforToken.SetRequestUri(Rec."Authorization URL");
            RequestMessageforToken.Method('POST');
            if ContentHeaders.Contains('Content-Type') then ContentHeaders.Remove('Content-Type');
            ContentHeaders.Add('Content-Type', 'application/json');
            RequestMessageforToken.Content(Content);
            IsSuccessful := HttpClient.Send(RequestMessageforToken, ResponseMessage);
            if not IsSuccessful then
                Error('Status Code: %1\ Reason : %2', ResponseMessage.HttpStatusCode, ResponseMessage.ReasonPhrase)
            else begin
                ResponseMessage.Content.ReadAs(ResponseText);
                JObject.ReadFrom(ResponseText);
                // Read the token from the response text and store the value on configuration page field Token Value.
                if JObject.Contains('token') then begin
                    JObject.Get('token', JToken);
                    JValue := JToken.AsValue();
                    AuthTokenvalue := Format(JValue);
                    PostmanAccessTokenValue := DelChr(AuthTokenvalue, '=', '"');
                    Rec."Authorization Token" := PostmanAccessTokenValue;
                    Rec.Modify();
                end
                else begin
                    Error('The "Authorization Token" is not generated.');
                end;

    Hope this help you,
    May other experts give you correct solution.

    Thank you,
    Shrey Chauhan
  • Scott_iTalent Profile Picture
    Community Manager on at
    HttpClient with Authorization Issue
    Thanks for coming back to the community and letting us know what worked, Greg Kujawa! Much appreciated!
  • Suggested answer
    Greg Kujawa Profile Picture
    289 on at
    HttpClient with Authorization Issue
    I had to change the RequestHeaders.Add to be RequestHeaders.TryAddWithoutValidation in order to get the header to work. So good now.
  • Greg Kujawa Profile Picture
    289 on at
    HttpClient with Authorization Issue
    And for a test, I tried the same call in PowerShell. Worked just fine with these headers set. Screen shot below.
     

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

Daivat Vartak – Community Spotlight

We are honored to recognize Daivat Vartak as our March 2025 Community…

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Kudos to the February Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 293,209 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,923 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156 Moderator

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans