Jump to content
nhardel

WinHttp Authentication not working as expected.

Recommended Posts

nhardel

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
Inververs

1) Port must be 17778. See _WinHttpConnect description

Share this post


Link to post
Share on other sites
nhardel

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
Inververs

Try with _WinHttpSimpleSSLRequest or _WinHttpSimpleSendSSLRequest

Share this post


Link to post
Share on other sites
nhardel

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
Inververs

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
nhardel

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
Inververs

send this headers: $sHeader = 'Authorization: Basic YWRtaW46' & @CRLF

 

  • Like 1

Share this post


Link to post
Share on other sites
nhardel

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

  • Similar Content

    • rcmaehl
      By rcmaehl
      Hi all, 

      Recently my work swapped from Cisco CTIOS to Finesse. This completely threw me off as I had been automating the Win32 application and I had never done IUIAutomation before. As such I've been messing around with the API and will be adding code as I figure it out. While I do have Supervisor access, I will likely not be adding functions for those features yet.
      Currently Available Functions:
      User API - Query and Set User Info
      Dialog API - Query and Set Call and other Dialog Info
      Queue API - Query Assigned Queues
      Team API - Query Users in a Team


      Changelog:
       
      Download:
       
    • Surya
      By Surya
      Hi everyone its been loooong since I posted here 
      I have been trying to convert this curl executable parameters into autoit using the winhttp com object;
      curl -F data_file=@my_audio_file.mp3 -F model=en-US "https://api.speechmatics.com/v1.0/user/41049/jobs/?auth_token=MmQ5MTk4jdsgjhgghstOGU5YS00OWFhLWghdgjshgdhbshj017###" any ideas guys
       
      PS: I am excited to post here after a looong time
    • Iznogoud
      By Iznogoud
      Hi,
      I was wondering if someone can help me to create an AutoIT script which can create a ticket in a TopDesk environment.
      The API is wel documented, but i have not enough knowlegde at this moment to get this up from the ground. If someone could help me or if i could hire / pay someone to help me with this, that would be great.
      Information about the API can be found here: https://developers.topdesk.com/
      Is there a place where i maybe can hire AutoIT professionals to help me with this?
      On freelancer.com is an option, but there are alot of people responding which doesn't know a thing about AutoIT.
    • Ascer
      By Ascer
      Hello
      Opertation Sys: Win7 x64
      Problem: Connecting to webs using TLS 1.1 +
      Description: WinHttp.WinHttpRequest.5.1 using TLS 1.0 by default, i need higher version to connect into some webs.
      Dim $oHttp = ObjCreate("WinHTTP.WinHTTPRequest.5.1") $oHttp.open ("GET", "https://howsmyssl.com/a/check", False) $oHttp.Option(9) = 128 ; 128 - TLS 1.0, 512 - TLS 1.1, 2048 - TLS 1.2, 2056 - TLS 1.1 & TLS 1.2 $oHttp.Send ConsoleWrite($oHttp.responseText & @CRLF) ; at end of the respond you can check your TLS version. Mine is: {"tls_version":"TLS 1.0","rating":"Bad"} Error: $oHttp.Option works only with parameter 128 (TLS 1.0) other values make error {Bad parameter}
      Additional: I've done this tutorial about enabling TLS in registry: <link>
      Thanks for support.
      Ascer
    • Ascer
      By Ascer
      1. Description.
      oAuth 2.0 is security system implemented by Google a few years ago. You are able to connect into your Google accounts and manage documents. In this UDF i show you how to pass first authorization process., this allow you to automate most of functions using API interface. 2. Requirements.
      Google account. oAuth.au3 Download 3. Possibilities
      ;============================================================================================================ ; Date: 2018-02-10, 14:21 ; ; Description: UDF for authorize your app with oAuth 2.0 Google. ; ; Function(s): ; oAuth2GetAuthorizationCode() -> Get Code for "grant". ; oAuth2GetAccessToken() -> Get "access_token" and "refresh_token" first time. ; oAuth2RefreshAccessToken() -> Get current "access_token" using "refresh_token". ; ; Author(s): Ascer ;============================================================================================================ 4. Enable your Google API.
          4.1. Video Tutorial not mine!
       YouTube     4.2 Screenshots from authorization process (Polish language) 
      Go to https://console.developers.google.com/apis/dashboard and accept current rules.  

       
      Next create an new project  

       
      Enter name of you new project and click Create  

       
      Google will working now, please wait until finish. Next go to enable your API interface, we make if for Google  

       
      Take "Gmail" in search input and after click in found result.  

       
      Click Enable interface, Google will working now.  

       
      Create your login credentials  

       
      Select Windows Interface (combobox), User credentials (radio) and click button what is need bla bla  

       
      Type name of a new client id for oAuth 2.0 and click Create a new Client ID.  

       
      Next configure screen aplication, type some name and click Next. Google will working now.  

       
      Last step on this website is download source with your credentials in *Json format.  

       
      Now you received a file named client_id.json, it's how it look in Sublime Text:  

       
      5. Coding.
      Now we need to call a some function to get access code.  
      #include <oAuth.au3> Local $sClientId = "167204758184-vpeues0uk6b0g4jrnv0ipq5fapoig2v8.apps.googleusercontent.com" Local $sRedirectUri = "http://localhost" oAuth2GetAuthorizationCode($sClientId, $sRedirectUri)  
      Function will execute default browser for ask you to permission.  

       
      Next Google ask you to permission for access to your personal details by application Autoit   

       
      Now you can thing is something wrong but all is ok, you need to copy all after  code= . It your access code.  

       
      Let's now ask Google about our Access Token and Refresh Token  
      #include <oAuth.au3> Local $sClientId = "167204758184-vpeues0uk6b0g4jrnv0ipq5fapoig2v8.apps.googleusercontent.com" Local $sClientSecret = "cWalvFr3WxiE6cjUkdmKEPo8" Local $sAuthorizationCode = "4/AAAPXJOZ-Tz0s6mrx7JbV6nthXSfcxaszFh_aH0azVqHkSHkfiwE8uamcabn4eMbEWg1eAuUw7AU0PQ0XeWUFRo#" Local $sRedirectUri = "http://localhost" Local $aRet = oAuth2GetAccessToken($sClientId, $sClientSecret, $sAuthorizationCode, $sRedirectUri) If Ubound($aRet) <> 4 then ConsoleWrite("+++ Something wrong with reading ResponseText." & @CRLF) Exit EndIf ConsoleWrite("Successfully received data from Google." & @CRLF) ConsoleWrite("access_token: " & $aRet[0] & @CRLF) ConsoleWrite("expires_in: " & $aRet[1] & @CRLF) ConsoleWrite("refresh_token: " & $aRet[2] & @CRLF) ConsoleWrite("token_type: " & $aRet[3] & @CRLF)  
      Important! When you received error 400 and output says: Invalid grant it means that your previous generated access_code lost validity and you need to generate new calling previus code. When everything is fine you should received a 4 informations about your: access_token, expires_in, refresh_token and token_type. Access_Token time is a little short so you need to know fuction possible to refresh it (tell Google that he should generate a new Token for you)  
      #include <oAuth.au3> Local $sRefreshToken = "1/ba8JpW7TjQH3-UI1BvPaXhSf-oTQ4BmZAbBfhcKgKfY" Local $sClientId = "167204758184-vpeues0uk6b0g4jrnv0ipq5fapoig2v8.apps.googleusercontent.com" Local $sClientSecret = "cWalvFr3WxiE6cjUkdmKEPo8" Local $sRedirectUri = "http://localhost" Local $aRet = oAuth2RefreshAccessToken($sRefreshToken, $sClientId, $sClientSecret) If Ubound($aRet) <> 3 then ConsoleWrite("+++ Something wrong with reading ResponseText." & @CRLF) Exit EndIf ConsoleWrite("Successfully received data from Google." & @CRLF) ConsoleWrite("access_token: " & $aRet[0] & @CRLF) ConsoleWrite("expires_in: " & $aRet[1] & @CRLF) ConsoleWrite("token_type: " & $aRet[2] & @CRLF)  
      6. Finish words
      If you followed all this above steps im sure that you received all informations required for coding your Google API (Gmail, Dropbox, YouTube, Calender etc. See next thread: [UDF] Gmail API - Email automation with AutoIt!
×