Jump to content
Sign in to follow this  
Nhardel

WinHttp Authentication not working as expected.

Recommended Posts

So I have been bashing my head in for a couple days and have searched both AutoIT forums and Thwack Forums for an answer.  I understand this could be hard to help sense I can't provide a server for someone to help me test against.  I am trying to use the WinHTTP.au3 to connect with Solarwinds Orion SDK thru REST/JSON api calls.  Here is the documentation that they provide.

https://github.com/solarwinds/OrionSDK/wiki/REST

I have been trying just to make a basic connection but for some reason cannot get past the authorization process with WinHTTP.  Here is my test code.

#Region Includes
#include <log4a.au3>
#include "WinHttp.au3"
#EndRegion

Global $sAddress = "https://usandl0213:17778/SolarWinds/InformationService/v3/Json/Query?query=SELECT+NodeID+FROM+Orion.NODES"
Global $array_URL = _WinHttpCrackUrl($sAddress)

;~ Row|Col 0
;~ [0]|https
;~ [1]|2
;~ [2]|usandl0213
;~ [3]|17778
;~ [4]|
;~ [5]|
;~ [6]|/SolarWinds/InformationService/v3/Json/Query
;~ [7]|?query=SELECT+NodeID+FROM+Orion.NODES

Global $hOpen = _winhttpOpen()
If @error Then
    _log4a_Fatal("Error intializing the usage of WinHTTP functions")
    Exit 1
EndIf

Global $hConnect = _winhttpConnect($hOpen, $array_URL[2])
If @error Then 
    _log4a_Fatal("Error specifying the initial target server of an HTTP request.") 
    _WinHttpCloseHandle($hOpen) 
    Exit 2 
EndIf 

Global $hRequest = _WinHttpOpenRequest($hConnect, _
                "GET", _
                "/SolarWinds/InformationService/v3/Json/Query?query=SELECT+NodeID+FROM+Orion.NODES", _
                "HTTP/1.1")
If @error Then 
    _log4a_Fatal(MsgBox(48, "Error", "Error creating an HTTP request handle.") 
    _WinHttpCloseHandle($hConnect) 
    _WinHttpCloseHandle($hOpen) 
    Exit 3 
EndIf 

_WinHttpAddRequestHeaders($hRequest, "Authorization: Basic YXV0b2l0X2xvZ2luOnRlc3Q=")
_WinHttpAddRequestHeaders($hRequest, "User-Agent: curl/7.20.0 (i386-pc-win32) libcurl/7.20.0 OpenSSL/0.9.8l zlib/1.2.3")
_WinHttpAddRequestHeaders($hRequest, "Host: usandl0213:17778")
_WinHttpAddRequestHeaders($hRequest, "Accept: */*")

_WinHttpSendRequest($hRequest)
If @error Then 
    MsgBox(48, "Error", "Error sending specified request.") 
    Close_request()
    Exit 4 
EndIf 

; Wait for the response 
_WinHttpReceiveResponse($hRequest) 
If @error Then 
    MsgBox(48, "Error", "Error waiting for the response from the server.") 
    Close_request()
    Exit 5
EndIf

 Global $sChunk, $sData
; See what's returned 
If _WinHttpQueryDataAvailable($hRequest) Then 
    Global $sHeader = _WinHttpQueryHeaders($hRequest) 
;~  ConsoleWrite(@crlf)
    ConsoleWrite($sHeader & @CRLF) 
    ; Read 
    While 1 
        $sChunk = _WinHttpReadData($hRequest) 
        If @error Then ExitLoop 
        $sData &= $sChunk 
    WEnd 
    ConsoleWrite($sData & @CRLF) ; print to console 

Else 
    MsgBox(48, "Error", "Site is experiencing problems.") 
EndIf 
 Close_request()

Func Close_request()
    ; Close open handles and exit 
    _WinHttpCloseHandle($hRequest) 
    _WinHttpCloseHandle($hConnect) 
    _WinHttpCloseHandle($hOpen)
EndFunc

I am definitely connecting to the server but get a 401 Unauthorized response.  Output of above script:

Header:

HTTP/1.1 401 Unauthorized
Cache-Control: private
Date: Thu, 27 Jul 2017 15:31:21 GMT
Content-Length: 1668
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
Set-Cookie: ASP.NET_SessionId=lgwin2qsbbrip2mxg01fot05; path=/; HttpOnly
Set-Cookie: TestCookieSupport=Supported; path=/
Set-Cookie: Orion_IsSessionExp=TRUE; expires=Thu, 27-Jul-2017 17:31:21 GMT; path=/
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-UA-Compatible: IE=9
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Same-Domain: 1
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block

Body:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><link rel="stylesheet" type="text/css" href="/orion/js/jquery-1.7.1/jquery-ui.css.i18n.ashx?l=en-US&v=42660.90.L&csd=%23b0b9c5;%23d2ddec;%2392add1;" />
<link rel="stylesheet" type="text/css" href="/orion/styles/orionminreqs.css.i18n.ashx?l=en-US&v=42660.90.L&csd=%23b0b9c5;%23d2ddec;%2392add1;" />
<link rel="stylesheet" type="text/css" href="/webengine/resources/steelblue.css.i18n.ashx?l=en-US&v=42660.90.L&csd=%23b0b9c5;%23d2ddec;%2392add1;" />
<link rel="stylesheet" type="text/css" href="/orion/ipam/res/css/sw-events.css.i18n.ashx?l=en-US&v=42660.90.L&csd=%23b0b9c5;%23d2ddec;%2392add1;" />
<script type="text/javascript" src="/orion/js/orionminreqs.js.i18n.ashx?l=en-US&v=42660.90.L"></script>
<script type="text/javascript" src="/orion/js/modernizr/modernizr-2.5.3.js.i18n.ashx?l=en-US&v=42660.90.L"></script>
<script type="text/javascript" src="/orion/js/jquery-1.7.1/jquery-1.7.1.framework.min.js.i18n.ashx?l=en-US&v=42660.90.L"></script>
<script type="text/javascript">(function(){var de=$(document.documentElement); de.addClass('sw-is-locale-en'); $.each(jQuery.browser,function(k,v){if(v===true){ de.addClass('sw-is-'+k); de.addClass('sw-is-'+k+'-'+parseInt(jQuery.browser.version)); }}); })();</script>
<script type="text/javascript">SW.Core.Loader._cbLoaded('jquery');</script>
<script type="text/javascript">SW.Core.Date._init(0,-14400000);</script>
<title>

</title></head>
<body>
<script>
    window.location = 'Login.aspx';
</script>
</body>
</html>

To me this looks like it if it is still looking for my credentials.   I did verify that things work as expected using Chrome and REST test client.  I do get certificate errors in IE if I try to go directly.  Bypass certificate issues and page will try to save out to .json file

 

Looking for any help.

Edited by nhardel

Share this post


Link to post
Share on other sites

I see that but when I change the line to

Global $hConnect = _winhttpConnect($hOpen, $array_URL[2],17778)

or

Global $hConnect = _winhttpConnect($hOpen, $array_URL[2], $array_URL[3])

I get an error back from _WinHTTPReceiveResponse.  I agree that there should be a port change but the server wont respond back with WinHTTP   of course this all works thru chrome and IE directly.   Could the DLL possible not allow non standard ports.  Surely not?      

Share this post


Link to post
Share on other sites

I tried using _WinHTTPSimpleSSLRequest() but I get no response.  Still fuzzy if I am using it correctly.  Code I used.

#Region Includes
#include <log4a.au3>
#include <Array.au3>
#include "WinHttp.au3"
#EndRegion

;~ Row|Col 0
;~ [0]|https
;~ [1]|2
;~ [2]|usandl0213
;~ [3]|17778
;~ [4]|
;~ [5]|
;~ [6]|/SolarWinds/InformationService/v3/Json/Query
;~ [7]|?query=SELECT+NodeID+FROM+Orion.NODES

Global $sAddress = "https://usandl0213:17778/SolarWinds/InformationService/v3/Json/Query?query=SELECT+NodeID+FROM+Orion.NODES"
Global $array_URL = _WinHttpCrackUrl($sAddress)

;~ _ArrayDisplay($array_url)

Global $hOpen = _winhttpOpen()
If @error Then
    _log4a_Fatal("Error intializing the usage of WinHTTP functions")
    Exit 1
EndIf


Global $hConnect = _winhttpConnect($hOpen, $sAddress)
If @error Then 
    _log4a_Fatal("Error specifying the initial target server of an HTTP request.") 
    _WinHttpCloseHandle($hOpen) 
    Exit 2 
EndIf 

Global $aRequest = _WinHttpSimpleSSLRequest($hConnect,"GET",$sAddress,Default,Default,Default,True,Default)
If @error Then 
    Switch @error
        Case 1
            _log4a_Fatal("could not open request.") 
        Case 2
            _log4a_Fatal("could not send request.") 
        Case 3
            _log4a_Fatal("could not receive response.") 
        Case 4
            _log4a_Fatal("$iMode is not valid.") 
    EndSwitch
EndIf

_arraydisplay($aRequest)

Close_request()

Func Close_request()
    ; Close open handles and exit 
    _WinHttpCloseHandle($hConnect) 
    _WinHttpCloseHandle($hOpen)
EndFunc

 

Edited by nhardel

Share this post


Link to post
Share on other sites

Did you try 17778 port? And 

_winhttpConnect

the second parameter is server name, not the full url... 

Edited by Inververs

Share this post


Link to post
Share on other sites

Okay so I made a few changes and I am getting something out of it again but I am still back to an authorization issue.  However I can see that it is not using the credentials correctly now.  Here is new code:

;solarwinds.au3
#Region Includes
#include-once 
#include <log4a.au3>
#include <Array.au3>
#include "WinHttp.au3"
#EndRegion
    
;~ GET https://localhost:17778/SolarWinds/InformationService/v3/Json/Query?query=SELECT+Uri+FROM+Orion.Pollers+ORDER+BY+PollerID+WITH+ROWS+1+TO+3+WITH+TOTALROWS HTTP/1.1
;~ Authorization: Basic YWRtaW46
;~ User-Agent: curl/7.20.0 (i386-pc-win32) libcurl/7.20.0 OpenSSL/0.9.8l zlib/1.2.3
;~ Host: localhost:17778
;~ Accept: */*


;~ Row|Col 0
;~ [0]|https
;~ [1]|2
;~ [2]|usandl0213
;~ [3]|17778
;~ [4]|
;~ [5]|
;~ [6]|/SolarWinds/InformationService/v3/Json/Query
;~ [7]|?query=SELECT+NodeID+FROM+Orion.NODES

Global $sAddress = "https://usandl0213:17778/SolarWinds/InformationService/v3/Json/Query?query=SELECT+NodeID+FROM+Orion.NODES"
Global $array_URL = _WinHttpCrackUrl($sAddress)
;~ _ArrayDisplay($array_url)
Global $hOpen = _winhttpOpen()
If @error Then
    _log4a_Fatal("Error intializing the usage of WinHTTP functions")
    Exit 1
EndIf

Global $hConnect = _winhttpConnect($hOpen, "usandl0213","17778")
If @error Then 
    _log4a_Fatal("Error specifying the initial target server of an HTTP request.") 
    _WinHttpCloseHandle($hOpen) 
    Exit 2 
EndIf 

Global $aRequest = _WinHttpSimpleSSLRequest($hConnect,"GET"  ,$array_url[6]&$array_url[7],Default    , Default,  Default, True        ,  Default,    "Admin",    Default,  1)
;~                 _WinHttpSimpleSSLRequest($hConnect, $sType, $sPath                    , $sReferrer,   $sDta, $sHeader, $fGetHeaders,   $iMode, $sCredName, $sCredPass, $iIgnoreCertErrors)
consolewrite(@error&@crlf)
If @error Then 
    Switch @error
        Case 1
            _log4a_Fatal("could not open request.") 
        Case 2
            _log4a_Fatal("could not send request.") 
        Case 3
            _log4a_Fatal("could not receive response.") 
        Case 4
            _log4a_Fatal("$iMode is not valid.") 
    EndSwitch
EndIf

_arraydisplay($aRequest)

 Close_request()

Func Close_request()
    ; Close open handles and exit 
;~  _WinHttpCloseHandle($hRequest) 
    _WinHttpCloseHandle($hConnect) 
    _WinHttpCloseHandle($hOpen)
EndFunc

And here is what the array spits out now

Row|Col 0
[0]|HTTP/1.1 401 Unauthorized
Date: Wed, 02 Aug 2017 15:38:38 GMT
Content-Length: 0
Server: Microsoft-HTTPAPI/2.0
WWW-Authenticate: Basic realm=""


[1]|
[2]|https://usandl0213:17778/SolarWinds/InformationService/v3/Json/Query?query=SELECT+NodeID+FROM+Orion.NODES

I had made the most basic user possible within the Solarwinds site "Admin" with no password just to try to get this working.

Share this post


Link to post
Share on other sites

Holy crap, I got the expected response back.  :D  Thanks so much Inververs.   Let me go play with this for a while and now that I can actually talk to the server see if I can figure out how to do the POST verb and understand JSON arrays.   Again, thanks a lot.

I did have to drop the '& @CRLF' to get this to work.   

Edited by nhardel

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By tarretarretarre
      About AutoIt-API-WS
      AutoIt-API-WS is a light weight web server with expressive syntax, with the sole purpose of wrapping your existing AutoIt app with little to no effort.
      With AutoIt-API-WS you can send and receive data between any application or framework, as long they can handle HTTP requests, which is an industry standard today.
      Like my other communcations UDF AutoIt-Socket-IO AutoIt-API-WS is heavily inspired from the big boys, but this time its Laravel and Ruby on Rails.
      Features Highlights
      No external or internal dependencies required RESTful mindset when designed Expressive syntax Small codebase Heavy use of Michelsofts Dictionary object Limitations
      Not complient with any RFC, so something important could be missing. Time will tell! One persons slow loris attack will kill the process forever. Example of implemetnation (With screenshots)
      This is a basic cRud operation with the RESTful mindset in use.
      #include "API.au3" #include <Array.au3> _API_MGR_SetName("My APP DB adapter") _API_MGR_SetVer("1.0 BETA") _API_MGR_SetDescription("This adapter allows you to get this n that") _API_MGR_Init(3000) _API_MGR_ROUTER_GET('/users', CB_GetUsers, 'string sortBy', 'Get all users, sortBy can be either asc or desc. asc is default') _API_MGR_ROUTER_GET('/users/{id}', CB_GetUsersById, 'int id*', 'Get user by id') While _API_MGR_ROUTER_HANDLE() WEnd Func DB_GetUsers() Local $userA = ObjCreate("Scripting.Dictionary") Local $userB = ObjCreate("Scripting.Dictionary") $userA.add('id', 1) $userA.add('name', 'TarreTarreTarre') $userA.add('age', 27) $userB.add('id', 2) $userB.add('name', @UserName) $userB.add('age', 22) Local $aRet = [$userA, $userB] Return $aRet EndFunc Func CB_GetUsers(Const $oRequest) Local $aUsers = DB_GetUsers() If $oRequest.exists('sortBy') Then Switch $oRequest.item('sortBy') Case Default Case 'asc' Case 'desc' _ArrayReverse($aUsers) EndSwitch EndIf Return $aUsers EndFunc Func CB_GetUsersById(Const $oRequest) Local Const $aUsers = DB_GetUsers() Local $foundUser = Null For $i = 0 To UBound($aUsers) -1 Local $curUser = $aUsers[$i] If $curUser.item('id') == $oRequest.item('#id') Then $foundUser = $curUser ExitLoop EndIf Next If Not IsObj($foundUser) Then Return _API_RES_NotFound(StringFormat("Could not find user with ID %d", $oRequest.item('#id'))) EndIf return $foundUser EndFunc When you visit http://localhost:3000 you are greeted with this pleasent view that will show you all your registred routes and some extra info you have provided.

      When you visit http://localhost:3000/users the UDF will return the array of objects as Json
       
      And here is an example of http://localhost:3000/users/1

       
      More examples can be found here
       
       (NEWEST 2020-09-21)
      Autoit-API-WS-1.0.3-beta.zip
      OLD VERSIONS
      Autoit-API-WS-1.0.0-beta.zip Autoit-API-WS-1.0.1-beta.zip
       
    • By Colduction
      Hi AutoIt Members and Programmers, i have a problem with Telegram UDF that does not work on some of my servers, Telegram is not restricted in these machines, here is console output in Windows 7 (Server):
      >"C:\Program Files (x86)\AutoIt3\SciTE\..\AutoIt3.exe" "C:\Program Files (x86)\AutoIt3\SciTE\AutoIt3Wrapper\AutoIt3Wrapper.au3" /run /prod /ErrorStdOut /in "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3" /UserParams +>20:20:40 Starting AutoIt3Wrapper (19.1127.1402.0} from:SciTE.exe (4.2.0.0) Keyboard:00000429 OS:WIN_7/Service Pack 1 CPU:X64 OS:X64 Environment(Language:0409) CodePage:0 utf8.auto.check:4 +> SciTEDir => C:\Program Files (x86)\AutoIt3\SciTE UserDir => C:\Users\.NetFramework\AppData\Local\AutoIt v3\SciTE\AutoIt3Wrapper SCITE_USERHOME => C:\Users\.NetFramework\AppData\Local\AutoIt v3\SciTE >Running AU3Check (3.3.14.5) from:C:\Program Files (x86)\AutoIt3 input:C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3 +>20:20:40 AU3Check ended.rc:0 >Running:(3.3.14.5):C:\Program Files (x86)\AutoIt3\autoit3.exe "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\tests\Test.au3" +>Setting Hotkeys...--> Press Ctrl+Alt+Break to Restart or Ctrl+BREAK to Stop. Test file for Telegram UDF (https://github.com/xLinkOut/telegram-udf-autoit). This file need a valid ChatID of a Telegram user who has already sent at least a message to the bot, and a valid token given by @BotFather. Insert this data in the source code. "C:\Users\.NetFramework\Desktop\telegram-udf-autoit-master\src\Telegram.au3" (1098) : ==> The requested action with this object has failed.: $oHTTP.Send() $oHTTP^ ERROR ->20:20:41 AutoIt3.exe ended.rc:1 +>20:20:41 AutoIt3Wrapper Finished. >Exit code: 1 Time: 1.56 It's really annoying problem in WinHTTP
    • By nacerbaaziz
      goodmorning autoit team
      today am comming with some winhttp problems, i hope that you can help me to solve them.
      the first problem
      is when opening a request
      my forums api allow me to delete any post using the api key
      all functions work, i mean post / get
      but when i tried to use the delete verb it's gave me an html 404 error
      here is what am tried
      #include "WinHttp.au3" ; Open needed handles Global $hOpen = _WinHttpOpen() Global $hConnect = _WinHttpConnect($hOpen, "xxxxxxxx.com") ; Specify the reguest: Global $hRequest = _WinHttpOpenRequest($hConnect, "Delete", "/vb/Api/posts/10447/?hard_delete=true", default, default) _WinHttpAddRequestHeaders($hRequest, "XF-Api-Key:xxxxx") _WinHttpAddRequestHeaders($hRequest, "XF-Api-User:xxxxx") ; Send request _WinHttpSendRequest($hRequest) ; Wait for the response _WinHttpReceiveResponse($hRequest) Global $sHeader = 0, $sReturned = 0 ; If there is data available... If _WinHttpQueryDataAvailable($hRequest) Then $sHeader = _WinHttpQueryHeaders($hRequest, $WINHTTP_QUERY_CONTENT_DISPOSITION) ;Or maybe: ; $sHeader = _WinHttpQueryHeaders($hRequest, BitOR($WINHTTP_QUERY_RAW_HEADERS_CRLF, $WINHTTP_QUERY_CUSTOM), "Content-Disposition") Do $sReturned &= _WinHttpReadData($hRequest) Until @error msgBox(64, "", $sReturned) endIf ; Close handles _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen)  
      and here is the error message
      <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>403 Forbidden</title> </head><body> <h1>Forbidden</h1> <p>You don't have permission to access /vb/Api/posts/10447/ on this server.<br /> </p> </body></html>  
      i hope you can help me 
      thanks in advance
    • By argumentum
      I can TCP/IP in AutoIt, hence, make a HTTP deamon. Now, how can I HTTPS to use SSL !??
      Well, Apache has this "mod_proxy.so" module that can let me have SSL and what not is in Apache.
      All that is needed is to tell Apache what I wanna do by editing httpd.conf .
      # Implements a proxy/gateway for Apache. # 1. Open /Applications/XAMPP/etc/httpd.conf # 2. Enable the following Modules by removing the # at the front of the line. # - LoadModule rewrite_module modules/mod_rewrite.so # - LoadModule proxy_module modules/mod_proxy.so # - LoadModule proxy_http_module modules/mod_proxy_http.so # # 3. Copy and Paste below to the bottom of httpd.conf # <IfModule mod_proxy.c> ProxyRequests On <Proxy *> Order deny,allow Allow from all </Proxy> ProxyVia Off ProxyPreserveHost Off ProxyPass /home/ http://127.0.0.1:84/home/ ProxyPassReverse /home/ http://127.0.0.1:84/home/ SetEnv proxy-nokeepalive 1 # ..since we are not using "keep-alive", we are using "close" </IfModule> ...et voila  
      I'm using XAMPP ( https://www.apachefriends.org/download.html )
      and this is my solution to avoid coding in PHP, as I feel more comfortable coding in AutoIt.
      A "muli-thread or concurrency" can be done by forking the socket ( https://www.autoitscript.com/forum/topic/199177-fork-udf-ish/ )
      but responses are under 20 ms., so I feel fine with a single thread.
      I modified an example ( attached below ), so can try out the concept.
      PS: I am not an Apache guru. I just discovered this and it opens a world of possibilities. In my case, I'm thinking of an API to query SQLite 
      PS2: I'm not gonna make Poll but do click like if you do  
       
      201673-json-http-post-serverlistener.au3
×
×
  • Create New...