Error Unsupported Grant Type - vba

I am trying to connect to an API, using MS Excel VBA. The parameters needed for login are grant type, username, and password.
I have came up with the code below, however i am getting the error :
{"error":"unsupported_grant_type"}
Can anyone enlighten me where i am doing it wrongly?
Sub test()
Dim objHttp As Object
Dim json As String
Dim user, password As String
user = "user1"
password = "password1"
json = "{""grant_type"":""password"",""username"":""" & user & """,""password"":""" & password & """}"
MsgBox json
Dim result As String
Set objHttp = CreateObject("MSXML2.XMLHTTP")
url = "http://dummywebsite.com"
objHttp.Open "POST", url, False
objHttp.SetRequestHeader "Content-type", "application/json"
objHttp.Send (json)
result = objHttp.ResponseText
MsgBox result
End Sub
The code is actually working, and it is due to user rights after testing with another user account.

Try:
Headers:
- Content-Type: application/x-www-form-urlencoded
- Accept-Charset: UTF-8
- Authorization: [Your Authorization Code]
Body:
username=[username]&password=[password]&grant_type=password

Related

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.

"Run-Time error '13': Type mismatch" in VBA for JSON extraction with JIRA API

New to the community here. I've done a decent amount of programming but I'm completely new to VBA. Never used it before until now and I was tasked with extracting JSON data from a Jira API into an Excel spreadsheet. I keep getting the error "Run-Time error '13': Type mismatch" and I'm not sure why. I know the error has to do with passing in incorrect types but I've tried changing the Json variable to a String with no success. Anyone have any ideas? Thanks!
By the way, this is just a trial Jira instance for testing the API functionality.
Sub test()
'Authenticate the user
Dim response As String
With CreateObject("Microsoft.XMLHTTP")
.Open "POST", "https://apitestsite.atlassian.net/rest/auth/1/session", False, "admin", "password"
.setRequestHeader "X-Atlassian-Token:", "nocheck"
.Send
response = .responseText
End With
'Query through JSON
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", "https://apitestsite.atlassian.net/rest/api/2/issue/CC-1", False, "admin", "password"
MyRequest.Send
Dim Json As Object
Set Json = JsonConverter.ParseJson(MyRequest.responseText)
MsgBox Json("fields")("summary")
End Sub
UPDATE: This is where I am at right now. Updated the code for the authentication and now no errors display from the compiler. Here is the JSONConverter class I am using: github.com/VBA-tools/VBA-JSON/blob/master/JsonConverter.bas. The issue now is that the returned JSON string says, "{"errorMessages":["Issue does not exist or you do not have permission to see it."],"errors":{}}". So I am able to connect to Jira just fine and return the JSON as a string, it's just that Jira is rejecting my credentials :/
Private JiraService As New MSXML2.XMLHTTP60
Private JiraAuth As New MSXML2.XMLHTTP60
Sub test()
'Authenticate the user
With JiraAuth
.Open "POST", "https://apitestsite.atlassian.net/rest/auth/1/session", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "X-Atlassian-Token:", "nocheck"
.send " {""username"" : ""admin"", ""password"" : ""password""}"""
sErg = .responseText
sCookie = "JSESSIONID=" & Mid(sErg, 42, 32) & "; Path=/Jira" '*** Extract the Session-ID
End With
With JiraService
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", "https://apitestsite.atlassian.net/rest/api/2/issue/CC-1", False
MyRequest.setRequestHeader "Content-Type", "application/json"
MyRequest.setRequestHeader "Accept", "application/json"
MyRequest.setRequestHeader "Set-Cookie", sCookie '*** see Create a "Cookie"
MyRequest.send
Dim Json As String
Json = MyRequest.responseText
MsgBox Json
End With
End Sub
This seems to return a valid JSON from the API, which is parseable from the Jsonconverter module.
You were using MyRequest object as possibly the wrong type of object. Elsewhere, you're relying on the MSXML2.XMLHTTP60 class.
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
So I removed the MyRequest and just worked with the JiraService object instead. You had a With JiraService block but you weren't actually using that object at all, you were executing against the WinHttpRequest object within that block.
I also declared all variables, and modified the auth string to use Const strings defined at top of module for user/password.
Option Explicit
Private JiraService As New MSXML2.XMLHTTP60
Private JiraAuth As New MSXML2.XMLHTTP60
Const user As String = "jiratestemail82#gmail.com"
Const pw As String = "password"
Sub test()
Dim sErg$, sCookie$, Json$
'Authenticate the user
With JiraAuth
.Open "POST", "https://apitestsite.atlassian.net/rest/auth/1/session", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "X-Atlassian-Token:", "nocheck"
.send " {""username"" : """ & user & """, ""password"" : """ & pw & """}"""
sErg = .responseText
sCookie = "JSESSIONID=" & Mid(sErg, 42, 32) & "; Path=/Jira" '*** Extract the Session-ID
End With
With JiraService
.Open "GET", "https://apitestsite.atlassian.net/rest/api/2/issue/CC-1", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Set-Cookie", sCookie '*** see Create a "Cookie"
.send
Json = .responseText
End With
Dim j As Object
Set j = JsonConverter.ParseJson(Json)
MsgBox j("fields")("summary")
End Sub

Sending values as parameters in HTTP GET using VBA request

So I am trying to send a basic request to a new API I'm testing out with the following script:
Sub CalcDemo()
TargetURL = "https://my-api-url.com"
Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1")
HTTPReq.Open "GET", TargetURL, False
HTTPReq.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
postData = "user=myUsername&password=myPassword"
HTTPReq.send (postData)
MsgBox (HTTPReq.responseText)
End Sub
But I'm getting the following error message: HTTP Status 401 - user and password should be specified as parameters on the request. I was under the impression that the manner in which postData is being passed above meant they are sent as parameters, but I guess I am wrong. How can I send a string of parameters?
It seems to me that the value of postData is not collecting the values of the variables myUsername or myPassword. you have to create the concatenated data like so:
postData = "user=" & myUsername & "&password=" & myPassword
I suppose that myUsername and myPassword are global variables. Otherwise you also need to pass them as arguments to your function.
Hope this helps!
As one comment has suggested, you are trying to send a post string usin a GET command. If you replace the folowing line, it should work:
HTTPReq.Open "GET", TargetURL, False
replaced by:
HTTPReq.Open "POST", TargetURL, False

VBA RESTful API GET Method issue

Hi I'm calling an API and using the winhttp request and the GET method. I'm passing a json style parameter in the send method but it just can't get accepted. I end up with the error message:
{"code":"INS03","description":"Event ID required","requestId":"_181603230829162847306080","data":{},"validationErrors":null}
Which seems weird because I am indeed passing the event id parameter, as follows:
inventory_URL = "https://api.stubhub.com/search/inventory/v1"
Dim oRequest As WinHttp.WinHttpRequest
Dim sResult As String
Set oRequest = New WinHttp.WinHttpRequest
With oRequest
.Open "GET", inventory_URL, True
.setRequestHeader "Authorization", "Bearer " & access_token
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Accept-Encoding", "application/json"
.send ("{""eventid"":""9445148""}")
.waitForResponse
sResult = .responseText
Debug.Print sResult
sResult = oRequest.Status
Debug.Print sResult
End With
Is there any issue with my code?
Thank you in advance,
Vadim
For GET request query string should be composed.
Your data can't be passed in Send but in query string:
.Open "GET", inventory_URL & "?eventid=9445148", True
Check GET vs POST.

Exchanging Authorization Code for Access Token for Google Calendar API with VBA and Oauth2

After successfully obtaining the authorization code, I am having trouble exchanging it for an access token and refresh token while trying to access the Google Calendar API. I get Error 404 Not Found. Here is my code:
Dim getTokenUrl As String
getTokenUrl = "https://accounts.google.com/o/auth2/token"
Dim getTokenBody As String
getTokenBody = "code=" & code & _
"&redirect_uri=urn:ietf:wg:oauth:2.0:oob" & _
"&client_id=xxxxxxx-xxxxxxxx.apps.googleusercontent.com" & _
"&client_secret={myLittleSecret}" & _
"&grant_type=authorization_code"
Dim Http As MSXML2.XMLHTTP60
Set Http = CreateObject("MSXML2.XMLHTTP.6.0")
With Http
.Open "POST", getTokenUrl, False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send(getTokenBody)
End With
Do While Http.ReadyState <> 4
Loop
Debug.Print Http.responseText
I have also tried putting everything in the url parameter of the .Open method and nothing in the .Send method:
Dim getTokenUrl As String
getTokenUrl = "https://accounts.google.com/o/oauth2/token&code=" & code & "&client_id=xxxxxx-xxxxxx.apps.googleusercontent.com&client_secret={myLittleSecret}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code"
Dim Http As MSXML2.XMLHTTP60
Set Http = CreateObject("MSXML2.XMLHTTP.6.0")
With Http
.Open "POST", getTokenUrl, False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send("")
End With
I have tried using WinHttp.WinHttpRequest instead of MSXML2.XMLHTTP.
I have tried using http://localhost instead of urn:ietf:wg:oauth:2.0:oob.
I have tried making http://localhost and urn:ietf:wg:oauth:2.0:oob url encoded.
All give Error 404 Not Found.
Can someone help point me in the right direction?
Finally figured it out--
The URL I was using was wrong--a one-letter type-o /forehead-slap/
instead of:
Dim getTokenUrl As String
getTokenUrl = "https://accounts.google.com/o/auth2/token"
it should have been:
Dim getTokenUrl As String
getTokenUrl = "https://accounts.google.com/o/oauth2/token"
note the oauth2 instead of just auth2
Geesh. Sometimes I just need more sleep.
Incidentally, I could only get it to work when I put only the base URL in the .Open request and the parameters in the .send() (rather than stringing them all together in to one URL and "POST"ing it).
Working like a charm now!