
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;
Leave a comment