Why won't this VBA program using ServerXMLHTTP60 authenticate properly? - vba

I have 4 different queries of IPR 1.2.3.4 (ip-reputation) to IBM's Xforce database, using basic authentication (base64 encoded), as well as URL-reputation. My version in python works great, printing out the appropriate JSON information:
...
if __name__ == '__main__':
apiKey = "1234...."
apiPwd = "5678..."
result = requests.get('https://xforce-api.mybluemix.net:443/ipr/1.2.3.4', verify=False,auth=(apiKey, apiPwd))
if result.status_code != 200:
print( "~ Bad Status Code: {}".format(result.status_code))
else:
print("~ The result is {}".format(result.status_code))
print("~ Rx Data={}".format(result._content))
The version in Go (using demisto's goxforce from github) works great. After setting my environment-variable key and password, I issue the commandline:
'xforceQuery -cmd ipr -q 1.2.3.4'
and it prints out the json information about 1.2.3.4, again, perfectly.
I use the browser-utility called 'Postman', specify basic authentication with my user/key and password, headers of Accept: application/json, Accept-Language: en, and Content-Type: application/json, and, again, it gives me the proper information (see .gif, below)
On the other hand, I try the same thing in VBA, and I get '401 Error: Not authorized'. What's wrong with this code?
Public Sub testXF()
Dim myKey As String
Dim myPass As String
myKey = "1234..."
myPass = "5678..."
pHtml = "xforce"
Dim ohttp As MSXML2.ServerXMLHTTP60
Set ohttp = New MSXML2.ServerXMLHTTP60
If timeout = 0 Then timeout = 60
ohttp.Open "GET", "https://xforce-api.mybluemix.net:443/ipr/1.2.3.4", False, myKey, myPass
With ohttp
.SetRequestHeader "Content-Type", "application/json"
.SetRequestHeader "Accept", "application/json"
.SetRequestHeader "Accept-Language", "en"
.SetTimeouts 0, 30 * 1000, 30 * 1000, timeout * 1000
.SetRequestHeader "Authorization", "Basic " + _
Base64Encode(myKey + ":" + myPass)
.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
End With
ohttp.Send ("")
With ohttp
pStatus = .status
pText = .ResponseText
pResponseHeaders = .GetAllResponseHeaders()
End With
Debug.Print "GET", pStatus, pText
Set ohttp = Nothing
End Sub

Related

API OAuth2 with VBA, Error: Missing grant type

I'm trying to receive an access token from the api of a partner via Oauth2.0.
When I use CURL I get the token but not in my VBA-script.
I get this error:
{"error":"invalid_request","error_description":"Missing grant type"}
The succesful CURL way is this:
curl -X POST -H "client_id:xxx" -u xxx:xxx"https://my.arrow.com/api/security/oauth/token" -d "grant_type=client_credentials"
I tried to send grant_type=client_credentials in different positions and spellings (in Body, as SetRequestHeader, grant_type=client_credentials or grant_type:client_credentials or grant_type, client_credentials) nothing helped, always same error.
This is the documentation for the API: https://my.arrow.com/more/developers/#section/Access-Token
Public Function API_MyArrow_Artikel(artikelBez) As String
Dim objHTTP As Object
Dim strHead As String, strClientId As String, strClientSecret As String, strBody As String
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
strClientId = "xxx"
strClientSecret = "xxx"
strUrl1 = "https://my.arrow.com/api/security/oauth/token"
strHead = strClientId & ":" & strClientSecret
lngADRNR = 674
objHTTP.Open "POST", strUrl1, False
objHTTP.SetRequestHeader "application", "x-www-form-urlencoded"
objHTTP.SetRequestHeader "client_id", strClientId
objHTTP.SetRequestHeader "client_secret", strClientSecret
objHTTP.SetRequestHeader "Authorization", "Basic " + Base64Encode(strHead)
'objHTTP.setRequestHeader "grant_type", "client_credentials"
objHTTP.SetTimeouts 10000, 10000, 10000, 10000 'Timeout (in milliseconds) to wait for timeout in each request phase (Resolve, Connect, Send, Receive)
objHTTP.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.Send "grant_type=client_credentials"
API_MyArrow_Artikel = objHTTP.responseText
End Function
The problem got solved. The correct way to use grant_type is as follows:
strUrl1 = "https://my.arrow.com/api/security/oauth/token?grant_type=client_credentials"
grant_type not in header or something else will work. Best is add to link.

Invalid_request Missing grant Type VBA Error Oauth 2.0

I'm struggling with this from last some hours.
I'm trying to receive an access token from the API of a partner via OAuth.
There's a small mistake in it that generates this error:
"error":"invalid_request","error_description":"Missing grant type"
Here is the VBA code I'm using in MS Access:
Public Function API_MyArrow_Artikel(artikelBez) As String
Dim objHTTP As Object
Dim strHead As String, strClientId As String, strClientSecret As String, strBody As String
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
strClientId = "xxx"
strClientSecret = "xxx"
strUrl1 = "https://my.arrow.com/api/security/oauth/token"
strHead = strClientId & ":" & strClientSecret
lngADRNR = 674
objHTTP.Open "POST", strUrl1, False
objHTTP.SetRequestHeader "application", "x-www-form-urlencoded"
objHTTP.SetRequestHeader "client_id", strClientId
objHTTP.SetRequestHeader "client_secret", strClientSecret
objHTTP.SetRequestHeader "Authorization", "Basic " + Base64Encode(strHead)
'objHTTP.setRequestHeader "grant_type", "client_credentials"
objHTTP.SetTimeouts 10000, 10000, 10000, 10000 'Timeout (in milliseconds) to wait for timeout in each request phase (Resolve, Connect, Send, Receive)
objHTTP.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.Send "grant_type=client_credentials"
API_MyArrow_Artikel = objHTTP.responseText
End Function
Any sort of suggestion to resolve is really appreciated as there are only some experts of OAuth 2.0 in here.
Thanks,
I found a solution to this.
There is some error in URL which needs to be fixed by adding below code to URL:
my.arrow.com/api/security/oauth/token?grant_type=client_credentials
And secondly replacing this:
objHTTP.SetRequestHeader "application", "x-www-form-urlencoded"
To this:
objHTTP.SetRequestHeader "content-type","application/x-www-form-urlencoded"
did the Job for me.

Access JIRA API from Excel with VBA-Web

I'm trying to access the JIRA API from Excel. Using the MSXML2.XMLHTTP.6.0 object works fine but using the WinHttp.WinHttpRequest.5.1 from the VBA-Web WebClient does not.
This works fine:
Function getJiraSessionId()
Set JiraAuth = CreateObject("MSXML2.XMLHTTP.6.0")
With JiraAuth
.Open "POST", "https://<our JIRA server>/tracker/rest/auth/1/session", False
.SetRequestHeader "Content-Type", "application/json"
.SetRequestHeader "Accept", "application/json"
.SetRequestHeader "User-Agent", "Jira-Automation"
.Send " {""username"" : ""...."", ""password"" : ""....""} "
sErg = .ResponseText
End With
...
End Function
This does not:
Function JiraLogin()
Dim JiraClient As New WebClient
JiraClient.BaseUrl = "https://<our JIRA server>/tracker/"
JiraClient.Insecure = True
JiraClient.TimeoutMs = 50000
Dim Abruf As New WebRequest
Abruf.Resource = "rest/auth/1/session"
Abruf.Method = WebMethod.HttpPost
Abruf.Format = WebFormat.Json
Abruf.UserAgent = "Jira-Automation"
Set Body = New Dictionary
Body.Add "username", "...."
Body.Add "password", "...."
Set Abruf.Body = Body
Dim Response As WebResponse
Set Response = JiraClient.Execute(Abruf)
...
End Function
The error message is:
ERROR - WebClient.Execute: -2147210493 (11011 / 80042b03), An error occurred during execute
-2147012739 (80072f7d): Im Support des sicheren Channels ist ein Fehler aufgetreten
I want to use VBA-Web because of its great tools but I can't. Any idea what is wrong? Thanks, Manfred.

How to deal with "Operation aborted" error when sending list update via Sharepoint REST?

I'm trying to build a VBA function that will update a value in a Sharepoint list:
Sub testUpdate()
Dim XmlHttp As MSXML2.XMLHTTP60
Dim result As String
Dim url As String
Dim body As String
Dim RequestDigest As String
Set XmlHttp = New MSXML2.XMLHTTP60
url = "https://sps.utility.xyz.com/sites/xyz/_api/web/lists/GetByTitle('REST Test List')/items(1)"
RequestDigest = GetDigest("https://sps.utility.xyz.com/sites/xyz")
body = "{ '__metadata': { 'type': 'SP.Data.REST_x0020_Test_x0020_ListListItem' }, 'Title': 'updating item with new title'}"
XmlHttp.Open "POST", url, False
XmlHttp.setRequestHeader "IF-MATCH", "*"
XmlHttp.setRequestHeader "accept", "application/json;odata=verbose"
XmlHttp.setRequestHeader "content-type", "application/json;odata=verbose"
XmlHttp.setRequestHeader "X-Http-Method", "MERGE"
XmlHttp.setRequestHeader "X-RequestDigest", RequestDigest
XmlHttp.setRequestHeader "Content-Length", Len(body)
XmlHttp.Send body
result = XmlHttp.responseText
End Sub
Function GetDigest(url As String)
Dim oHttp As New MSXML2.XMLHTTP60
Dim s As String
Dim l1 As Long
Dim l2 As Long
With oHttp
.Open "POST", url + "/_api/contextinfo", False
.setRequestHeader "content-type", "application/json;odata=verbose"
.Send ""
End With
s = oHttp.responseText
l1 = InStr(1, s, "FormDigestValue")
If l1 > 10 Then
l1 = l1 + 16
l2 = InStr(l1, s, "</d:FormDigestValue")
End If
If l2 > 10 Then GetDigest = Mid$(s, l1, l2 - l1)
Set oHttp = Nothing
End Function
But when testUpdate gets to the line:
XmlHttp.Send body
it throws this error:
Run-time error '-2147467260 (80004004)':
Operation aborted
Despite the error, the update succeeds--the list item's Title value changes.
Is it safe for me to simply handle this exception and bypass the error, or is it indicating that there is a real problem that I need to resolve?
The api call requires authentication. I managed to use WinHTTP to authenticate the request based on the current user, I am assuming that they have access in the below. I get a 204 response and my list item updates correctly. (the iteration is because I was testing performance and can be removed).
Tools>references>Microsoft WinHttp Services Version 5.1
Private Sub UpdateItem2(ID, strFormDigest As String, iteration)
Dim sUrl As String
sUrl ="https://123.Sharepoint.net/sites/123/_api/web/lists/getbytitle('MyDemoList')/items(" & ID & ")"
Dim oRequest As WinHttp.WinHttpRequest
Dim sResult As String
sEnv = "{ '__metadata': { 'type': 'SP.Data.MyDemoListListItem' }, 'Title': 'TEST" & iteration & "' }"
Set oRequest = New WinHttp.WinHttpRequest
With oRequest
.Open "POST", sUrl, True
.setRequestHeader "IF-MATCH", "*"
.setRequestHeader "X-HTTP-Method", "MERGE"
.setRequestHeader "accept", "application/json;odata=verbose"
.setRequestHeader "X-RequestDigest", strFormDigest
.setRequestHeader "content-type", "application/json;odata=verbose"
.SetAutoLogonPolicy AutoLogonPolicy_Always
.send sEnv
.waitForResponse
End With
End Sub

xmlhttp POST isn't working

I'm trying to post transactions to server using a middleware client (it's called Cohesion). Below is my code (asp):
Dim xmlhttp 'As Object
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.Open "POST", "http://server_ip/Databox-dr/CohesionConnect.asmx/GetHostReply", False
'using only http://server_ip/Databox-dr/CohesionConnect.asmx doesn't work, either
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
'xmlhttp.setRequestHeader "Content-Length", "128"
xmlhttp.send "50000000000MSUF"
Set xmlhttp = Nothing
The documentation I have (and that's all of it) is tellin me this:
HTTP POST
The following is a sample HTTP POST request and response. The placeholders shown need to be replaced with actual values.
POST /DATABOX-DR/CohesionConnect.asmx/GetHostReply HTTP/1.1
Host: server_ip
Content-Type: application/x-www-form-urlencoded
Content-Length: length
sTran=string
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://fidelityifs.com/webservices">string</string>
(length and string need to replaced with real values)
What am I doing wrong? How can I set the string length?
Thanks!!
Try this:
Dim xmlhttp As Object
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.Open "POST", "http://server_ip/Databox-dr/CohesionConnect.asmx/GetHostReply", False
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
tosend = "50000000000MSUF"
s = "sTran=" & tosend
xmlhttp.setRequestHeader "Content-Length", Len(s)
xmlhttp.send s