Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an MVC API with Windows Authentication from VBA

I have developed a MVC Application, which, for the purpose of this question only has one controller:

Public Function GetValue()
    Return User.Identity.Name
End Function

The application is to be used on an Intranet network, therefore, I have set it to 'Windows Authentication'

The aim is to query this application, through VBA.

Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
With objHTTP
    .Open "GET", URL, False
    .setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    .setRequestHeader "Content-type", "application/json"
    .setRequestHeader "data-type", "json"
    .send
    .WaitForResponse
    sResult = .ResponseText
End With
Debug.Print (sResult)

If I run the application locally (ie. debug on the computer that is running Excel), it works through Chrome (accessing localhost:xxxxx/api/name returns an xml file with my ActiveDirectory username).

The VBA routine works fine as well, and the Output window displays the XML I get in Chrome.

Now, if I publish the project to the IIS server, it still works through Chrome (accessing myserver/api/name returns an xml file with my ActiveDirectory username). However, when I run the VBA module, it returns an Error 401:

Error:401 - Unauthorized: Access is denied due to invalid credentials.

The fact that it works in browsers leads me to believe that server-side configuration is OK, and that I need to tweak something in my VBA.

I have to admit that I am a bit clueless at this point... Thank you for any leads you may give me :)

like image 457
Maxime Avatar asked Oct 21 '25 15:10

Maxime


1 Answers

Thanks to @SWa comment, I solved this with a minor tweak to the function: Switching to WinHttpRequest and using setAutoLogonPolicy 0

Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
With objHTTP
    .Open "GET", URL, False
    .setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    .setRequestHeader "Content-type", "application/json"
    .setRequestHeader "data-type", "json"
    .setAutoLogonPolicy 0
    .send
    .WaitForResponse
    sResult = .ResponseText
End With
Debug.Print (sResult)
like image 65
Maxime Avatar answered Oct 23 '25 08:10

Maxime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!