Troubles with http basic auth

Hi,

I’m trying to create an http basic auth header to use with the http client. I’m brand new to prolog, so please forgive my lack of knowledge. Please find my latest attempt below. I don’t really understand what I’m doing wrong.

:- use_module(library(http/http_client)).
:- use_module(library(http/http_json)).
:- use_module(library(base64)).


basic_auth(Header) :-
  format(atom(Credentials), '~w:~w', ['user', 'password']),   % Concatenate username and password
  base64(Credentials, Encoded),                               % Base64 encode the concatenated string
  format(atom(Header), 'Authorization: Basic ~w', [Encoded]). % Create the header with the "Basic" scheme



% Base URL for the server
base_url('http://localhost/api').

% Create a doc
create_doc(Document) :-
  base_url(BaseURL),                                                                    % get base url
  basic_auth(Header),                                                                   % get auth header
  atomic_list_concat([BaseURL, '/document'], URL),                                      % build full url
  http_post(URL, json(_{name: testme}), _, [authorization(Header), json_object(dict)]). % post to server

I get the error below:

ERROR: Domain error: authorization' expected, found ‘Authorization: Basic dXNlcjpwYXNzd29yZA==’’

Thanks,
-S

Try authorization(basic(User,Passwd)). The library will do the encoding for you. Alternatively, create the header as you do and use the option to add arbitrary headers.

Hi,

Are you referring to http_set_authorization/2? I get an “Unknown procedure” error for authorization/1.

Thanks,
-S

No. I’m referring to the option you are already passing to http_post/4. All you need to do is change the value you pass in.

http_set_authorization/2 allows you to set the authorization for a domain without mentioning this explictly in the http_post/4 call.

Hi,

That works. I tried to use the http_set_authorization/2 as well, but it does not or at least I don’t understand how it works. I was trying to avoid the need to specify the credentials in every call.

I appreciate your help.

Thanks,
-S

Should be by calling

 http_set_authorization('http://localhost/api', basic("bob", "secret")).

Hi,

I actually tried that and a few other variations, but I couldn’t get it to work for me. No worries though, your previous reply solved my problem.

Thanks Again,
-S