httpclient: basic authentication

gbierkensgbierkens Member Posts: 49
I'm experimenting with integrating Dynamics NAV with a REST API.
I have created an API with basic authentication.

Now I would like NAV (2016) to send http requests with basic authentication.
I'm fairly new to dotnet interop so forgive me if I ask a stupid question :)

I Use the following code to send the post request

Method := 'POST';
HttpStringContent := json string

HttpClient := HttpClient.HttpClient;
HttpClient.BaseAddress := Uri.Uri(BaseUrl);

HttpResponseMessage := HttpClient.PostAsync(Method,HttpStringContent).Result;


When I disable authentication in my webservice this works like a charm.

I tried the following this to add authentication to this request.

1. networkcredentials
NetworkCredential := NetworkCredential.NetworkCredential('abc','test');
HttpClientHandler := HttpClientHandler.HttpClientHandler;
HttpClientHandler.Credentials := NetworkCredential;

HttpClient := HttpClient.HttpClient(HttpClientHandler );

this doesn't seem to do anyting.

2. default request headers
HttpClient := HttpClient.HttpClient();
HttpClient.BaseAddress := Uri.Uri(BaseUrl);
HttpClient.DefaultRequestHeaders.Add('Authorisation','Basic');
HttpClient.DefaultRequestHeaders.Add('PHP_AUTH_USER','abc');

As you can probably see these are just trials which I distilled from several stack overflow posts.
But none of them are working. Can someone point me in the right direction?

Answers

  • JonasAJonasA Member Posts: 28
    I think the choice of HttpClient might be wrong.

    This works for me (I use Fiddler to record what http headers are sent):
    HttpWebRequest := HttpWebRequest.Create('url');
    HttpWebRequest.Credentials := Credential.NetworkCredential('myusername', 'mypassword');
    HttpWebRequest.Method := 'POST';
    

    Types:
    Name	DataType	Subtype	Length
    HttpWebRequest	DotNet	System.Net.HttpWebRequest.'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'	
    Credential	DotNet	System.Net.NetworkCredential.'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
    


    You can find additional inspiration in codeunit 1297 in Dynamics NAV 2016.

Sign In or Register to comment.