AndreaNobili
AndreaNobili

Reputation: 42967

How can I set the NTLM credential (as in my .NET controller) into a CURL request?

I am working on a .NET project. Into a controller of this project I am calling an external API specifying an authentication, in this way:

private NetworkCredential myCreds = new NetworkCredential("MYUSERNAME", "MYPASSWORD", "MYDOMAIN");

private CredentialCache = new CredentialCache();

string jsonRequest = urlBaseProtocolloApi + "/api/MY_ENDPOINT";

credCache.Add(new Uri(jsonRequest), "NTLM", myCreds);

HttpWebRequest spRequest = (HttpWebRequest)HttpWebRequest.Create(jsonRequest);
spRequest.Credentials = credCache;
spRequest.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0";
spRequest.Method = "GET";
spRequest.Accept = "application/json;odata=verbose";

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

HttpWebResponse endpointResponse = (HttpWebResponse)spRequest.GetResponse();

It works perfectly fine.

As you can see I am using this NTLM protocol to perform the authentication into the called API.

My problem is that, for test reason, I want to perform this call using curl instead passing from my .NET controller.

I tried in this way:

curl -X POST -k -d @invio_a_protocollo.json https://my_machine:13003/API_CONTEXT/api/MY_ENDPOINT --header "Content-Type:application/json

but obviously, since I'm not passing the credentials, I am obtaining this error message:

{"Message":"Authorization has been denied for this request."}

How can I try to set this NTLM on my curl request?

Upvotes: 1

Views: 2210

Answers (1)

georgeok
georgeok

Reputation: 5716

Your .net is automatically using kerberos or ntlm (aka WIA). In curl you have to use the --ntlm or --negotiate or --anyauth and the --user flags.

Some examples:

This will try ntlm: curl -X POST -k --ntlm --user domain\user:password -d @invio_a_protocollo.json https://my_machine:13003/API_CONTEXT/api/MY_ENDPOINT --header "Content-Type:application/json

This will try negotiate: curl -X POST -k --negotiate --user user:password -d @invio_a_protocollo.json https://my_machine:13003/API_CONTEXT/api/MY_ENDPOINT --header "Content-Type:application/json

This will try kerberos or ntlm depending on the IIS setup: curl -X POST -k --anyauth --user user:password -d @invio_a_protocollo.json https://my_machine:13003/API_CONTEXT/api/MY_ENDPOINT --header "Content-Type:application/json

Known bugs: There two known bugs in curl related to ntlm HTTPS and POST requests:

  1. Curl drops the payload for POST requests with ntlm: https://github.com/curl/curl/issues/2431
  2. NTLM return 401 when "Extended protection" is Required by IIS: https://github.com/curl/curl/issues/3280. To fix the issue turn off extended protection if you can and live with the security traits (https://learn.microsoft.com/en-us/iis/configuration/system.webserver/security/authentication/windowsauthentication/extendedprotection/#how-to).

Upvotes: 2

Related Questions