VBA Authorization oauth2 API - json

Been stuck on this for a few days now.
Trying to obtain access token from an API with oauth2 authentication.
But I keep getting '401 Unauthorized',
"Full authentication is required'
My gues is i'm doing something wrong with the
.SetRequestHeder "Authorization", "basic " + (base64 encoded)
Here's the code so far: (worked with another API)
Username = "myusername"
Password = "myclientsecret"
PasswordnUsername = Password & ":" & Username
argumentString = "?grant_type=password&username=myusername&password=mypassword"
Set xmlhttp = CreateObject("MSXML2.XMLHTTP.6.0")
xmlhttp.Open "POST", "https://api.url/partner/oauth/token", False
xmlhttp.SetRequestHeader "Authorization", "basic " + mdl_API_MB_ACCESS_TOKEN.Base64Encode(PasswordnUsername)
xmlhttp.SetRequestHeader "x-api-key", "myxapicode"
xmlhttp.Send (argumentString)

Related

Excel 2010 VBA - Trying to retrieve data from site using API JSON

Thank you in advance for any help!! First time using api calls. Trying to input an ISBN into a cell the retrieving information from my inventory file located at artofbooks.com Their documentation for their API calls is not that great. This is my code and I am getting a "bad token" error.
sub test
creds = EncodeBase64("{ AOB_AUTH_USER : cottagebooks, AOB_AUTH_PW : xxxxxx }")
isbn = Cells(5, 3).Value
Set objHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
URL = "https://www.theartofbooks.com/api/2.0/item=2010101257"
objHttp.Open "GET", URL, False
objHttp.SetRequestHeader "Content-Type", "multipart/form-data"
objHttp.SetRequestHeader "Accept", "application/xml"
objHttp.SetRequestHeader "Authorization:", "Bearer " & creds
objHttp.Send
strResponseStatus = objHttp.Status
strresponsetext = objHttp.ResponseText
strresponsetext = CStr(strresponsetext)
MsgBox strresponsetext
end sub

Getting unsupported_grant_type when exchanging code for a token

Using VBA, I am able to authenticate the user and obtain 'code' successfully using my sandbox account. However, when I attempt to exchange the permission token for an access token, I get status code 400, Bad Request (unsupported_grant_type). I searched for similar problems and tried many suggestions to no avail. I have been successful in using the implicit grant process, but would like to now switch to code grant. I validated the Base64 conversion using an online tool. It worked fine. The process looks very simple and straight forward. Any help is much appreciated.
The VBA code I'm using follows:
strURL = "https://account-d.docusign.com/oauth/token"
strAuthorization = Base64EncodeString(gstrIntegrationKey & ":" & gstrSecretKey)
Set objJSON = New Dictionary
objJSON.Add "grant_type", "authorization_code"
objJSON.Add "code", strCode
strJSON = JsonConverter.ConvertToJson(objJSON)
Set objHTTP = New MSXML2.XMLHTTP60
objHTTP.Open "POST", strURL, False
objHTTP.setRequestHeader "Content-Type: ", "application/x-www-form-urlencoded"
objHTTP.setRequestHeader "Accept: ", "application/json"
objHTTP.setRequestHeader "Authorization: ", "Basic " & strAuthorization
objHTTP.send strJSON
Do Until objHTTP.ReadyState = 4
DoEvents
Loop
strResponse = Replace(objHTTP.responseText, "null", """null""")
If objHTTP.Status <> 200 Then
If Not DocuSignErr(strResponse, objHTTP.Status, objHTTP.statusText) Then Stop
GoTo FailedExit
End If
The body should be form URL encoded not JSON encoded. Instead of using the Dictionary and running it through JsonConverter.ConvertToJson, you should encode it in as a form (e.g., value1=a&value2=b). So, you can do something like this:
strURL = "https://account-d.docusign.com/oauth/token"
strAuthorization = Base64EncodeString(gstrIntegrationKey & ":" & gstrSecretKey)
Set objHTTP = New MSXML2.XMLHTTP60
objHTTP.Open "POST", strURL, False
objHTTP.setRequestHeader "Content-Type: ", "application/x-www-form-urlencoded"
objHTTP.setRequestHeader "Accept: ", "application/json"
objHTTP.setRequestHeader "Authorization: ", "Basic " & strAuthorization
objHTTP.send "grant_type=authorization_code&code=" & strCode
...

API-request over XMLHTTP (IIS) failing

I am trying to send a request (POST) to an API using the XMLHTTP.6.0 object.
When running the same procedure in Postman it works like a charm - but when running it in VB over IIS (ASP) the responding server seems to not even receive the authorization headers specified.
Have been trying to figure out why this occurs all day without no luck.
Anyone have av idea why the Authorization header is no retreived by the remote server?
<%
Function ASPPostJSON(url)
Dim objXmlHttp
Set objXmlHttp = Server.CreateObject("Msxml2.XMLHTTP.6.0")
objXmlHttp.Open "POST", url, false, "nouser", "nopwd"
objXmlHttp.setRequestHeader "Accept", "*/*"
objXmlHttp.SetRequestHeader "Authorization", "Basic VGVzdEZpbmFuczpHUTJUR05KUUdFWURNTlJURzQzR0laUldHNVFXR1pSVA=="
objXmlHttp.SetRequestHeader "cache-control", "no-cache"
objXmlHttp.SetRequestHeader "content-length", "26"
objXmlHttp.SetRequestHeader "Content-Type", "application/json"
'send the json string to the API server
objXmlHttp.Send "{""PNR"": 194803234857 }"
'If objXmlHttp.Status = 200 Then
ASPPostJSON = CStr(objXmlHttp.ResponseText)
'end if
'return the response from the API server
Response.write(ASPPostJSON)
Set objXmlHttp = Nothing
End Function
'call the function and pass the API URL
call ASPPostJSON("https://api.testserver.com/v2/person")
%>

How to get json response in classic asp post request with https url

set urlname = "https://URL/sso/json/sessions/?_action=validate"
set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
xmlhttp.Open "POST", urlname, false
xmlhttp.setRequestHeader "Content-Type", "application/json"
xmlhttp.setRequestHeader "ms-sso", encryptedTicket
xmlhttp.send
set status = xmlhttp.responseText
response.Write("<script language=javascript>console.log(' statuss : " & status & "'); </script>")
I have above code block:
I am trying to call https URL using POST request
Its just basically decrypt the token (ms-sso) and gives GUID in response.
but I am getting a black response in status code and responseText.
but it works fine if I checked with Fiddler :
POST:"https://URL/sso/json/sessions/?_action=validate"
Content-Type: application/json
ms-sso: AQIC5wM2LY4SfcyB2ttvMve81T42_U1gUOWFv4grmOSRssg.*AAJTSQACMDIAAlNLABM0MTQxMTQ5MjM5MzE3OTA5MTA3AAJTMQACMTI.*
{"valid":true,"uid":"8FC1D617-8E32-45E2-9417-0323491765D2","realm":"/msusers"}
Why this is happening ? any idea?

CURL Equivalent to POST JSON data using VBA

I know this is similar to some previously asked questions, but something is still not working for me. How can the following command:
curl -X POST --data #statements.json -H "Content-Type: application/json" --user username:password -H "x-experience-api-version: 1.0.0" https://MYLRS.waxlrs.com/TCAPI/statements
be replicated in VBA?
Extra Information:
This relates to a Hosted TIN CAN (xAPI) Learning Record Store called WaxLRS (by SaltBox). The above example comes from here:
http://support.saltbox.com/support/solutions/articles/1000083945-quick
I have an account (free tinkerers account, no CC required to setup) and have generated what I believe to be the required username & password combination. The credentials are termed 'Identifier' & 'Password' and appear under a heading: Basic Authentication Credentials.
No matter what I do I get an error message:
<html>
<head><title>Unauthorized</title></head>
<body>
<h1>Unauthorized</h1>
<p>This server could not verify that you are authorized to
access the document you requested. Either you supplied the
wrong credentials (e.g., bad password), or your browser
does not understand how to supply the credentials required.
<br/>
<!-- --></p>
<hr noshade>
<div align="right">WSGI Server</div>
</body>
</html>
I believe that the example is expecting the JSON payload to be obtained from a file, but I am loading it into a string. I don't expect this to be contributing to the problem, I have compared my string with the example provided using NP++ Compare and it matches.
My code so far is:
url = "https://xxxxxxx.waxlrs.com/TCAPI/statements"
Set pXmlHttp = CreateObject("WinHttp.WinHttpRequest.5.1") 'MSXML2.XMLHTTP")
pXmlHttp.Open "POST", url, False
pXmlHttp.setRequestHeader "Content-Type", "application/json"
'pXmlHttp.setRequestHeader "Authorization", "Basic xxxxxxt8wfB6JYerYCz:xxxxxx1FOd29J1s6G2"
pXmlHttp.SetCredentials "xxxxxxt8wfB6JYerYCz", "xxxxxx1FOd29J1s6G2", 0
pXmlHttp.setRequestHeader "x-experience-api-version", "1.0.0"
pXmlHttp.send (stringJSON)
Set pHtmlObj = CreateObject("htmlfile")
pHtmlObj.body.innerHTML = pXmlHttp.responseText
apiWaxLRS = pXmlHttp.responseText
Questions/Answers that helped:
Send a JSON string to a RESTful WS from Classic ASP
https://stackoverflow.com/a/17063741/3451115
How to POST JSON Data via HTTP API using VBScript?
But, I'm still at a loss as to how to replicate the CURL statement in VBA
Try to make basic authorization as shown in the below example:
Sub Test()
sUrl = "https://xxxxxxx.waxlrs.com/TCAPI/statements"
sUsername = "*******************"
sPassword = "******************"
sAuth = TextBase64Encode(sUsername & ":" & sPassword, "us-ascii")
With CreateObject("WinHttp.WinHttpRequest.5.1")
.Open "POST", sUrl, False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Authorization", "Basic " & sAuth
.setRequestHeader "x-experience-api-version", "1.0.0"
.send (stringJSON)
apiWaxLRS = .responseText
End With
End Sub
Function TextBase64Encode(sText, sCharset)
Dim aBinary
With CreateObject("ADODB.Stream")
.Type = 2 ' adTypeText
.Open
.Charset = sCharset
.WriteText sText
.Position = 0
.Type = 1 ' adTypeBinary
aBinary = .Read
.Close
End With
With CreateObject("Microsoft.XMLDOM").CreateElement("objNode")
.DataType = "bin.base64"
.NodeTypedValue = aBinary
TextBase64Encode = Replace(Replace(.Text, vbCr, ""), vbLf, "")
End With
End Function