HTTP Basic Authentication with the AL HttpClient

Business Central and the AL language have made web service code much easier with the HttpClient and Json types available. Handling the HTTP Authorization header is easier too with the TempBlob table, which can now encode the basic authentication string using base64.

See below for an example of how to add a basic authorisation header to the AL HttpClient:

procedure AddHttpBasicAuthHeader(UserName: Text[50]; Password: Text[50], var HttpClient : HttpClient);
var
  AuthString: Text;
  TempBlob: Record TempBlob temporary;
begin
  AuthString := STRSUBSTNO('%1:%2, UserName, Password);
  TempBlob.WriteTextLine(AuthString);
  AuthString := TempBlob.ToBase64String();
  AuthString := STRSUBSTNO('Basic %1', AuthString);
  HttpClient.DefaultRequestHeaders().Add('Authorization', AuthString);
end;

Update 2019-07-04: Thanks to Arend-Jan Kauffmann commenting on LinkedIn to point out there is an even easier way to get the Base64 encoding done using Codeunit 10 “Type Helper”:

procedure AddHttpBasicAuthHeader(UserName: Text[50]; Password: Text[50], var HttpClient : HttpClient);
var
  AuthString: Text;
  TypeHelper: "Type Helper";
begin
  AuthString := STRSUBSTNO('%1:%2, UserName, Password);
  AuthString := TypeHelper.ConvertValueToBase64(AuthString);
  AuthString := STRSUBSTNO('Basic %1', AuthString);
  HttpClient.DefaultRequestHeaders().Add('Authorization', AuthString);
end;

5 thoughts on “HTTP Basic Authentication with the AL HttpClient”

  1. Hi after adding the above details, i am getting misused header name error while sending the details, any idea about this.

  2. Hi Varun, are you able to share a code snippet showing how you create the auth string and add the header? Also which version of NAV/BC are you working on? I recall a similar error when using the .NET libraries in NAV as it doesn’t like you directly adding an Authorisation header to the HTTPRequest, and requires the use of a specific function to add credentials.

  3. In BC ocktober 2019 release (version 15) its looks like the .ConvertValueToBase64 is removed from the codeunit 10 (Type Helper). Do you know if this procedure has been just moved or completly removed?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.