0

This is the structure of how to get a Xero Access Token from an OAuth 2.0 Xero Authorization Code according to https://developer.xero.com/documentation/oauth2/auth-flow

POST https://identity.xero.com/connect/token
authorization: "Basic " + base64encode(client_id + ":" + client_secret)
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&code=xxxxxx
&redirect_uri=https://myapp.com/redirect

I have created the following vb.net framework 4.6.1 Winforms code:

Dim base64Decoded As String = xeroClientId & ":" & xeroClientSecret
Dim base64Encoded As String
Dim data As Byte()
data = System.Text.ASCIIEncoding.ASCII.GetBytes(base64Decoded)
base64Encoded = System.Convert.ToBase64String(data)

Dim Basic As String = "Basic " & base64Encoded

Dim getTenant As RestClient = New RestClient("https://identity.xero.com/connect/token")
getTenant.Timeout = -1
Dim request = New RestRequest(Method.POST)
request.AddHeader("authorization", Basic)
request.AddHeader("Content-Type", "application/x-www-form-urlencoded")

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls

request.AddParameter("grant_type", "authorization_code", ParameterType.RequestBody)
request.AddParameter("code", xeroCode, ParameterType.RequestBody)
request.AddParameter("redirect_uri", String.Format("http://localhost:5000/"), ParameterType.RequestBody)

Dim response As IRestResponse = getTenant.Execute(request)

This code gives me the error

"unsupported_grant_type"

Isn't request.AddParameter("grant_type", "authorization_code", ParameterType.RequestBody) the right way of creating grant_type=authorization_code in the request body? What am I missing?

Any help would be appreciated.

  • If this is RestSharp, the documentation says "If this parameter is set, its value will be sent as the body of the request. Only one RequestBody parameter is accepted - the first one.". So you need to combine the various parts and call AddParameter once, by the look of it. I don't use that API (I just do raw HTTP Get, Put or Post calls) but I just stick the names and parameters into a string with & between them, and put that string in the body. – droopsnoot Jul 08 '20 at 17:32
  • By that I mean I have "grant_type=whatever&code=something" in the body, each parameter and value in that format. – droopsnoot Jul 08 '20 at 18:28
  • Thanks @droopsnoot. Lifesaver. I removed ParameterType.RequestBody from the AddParameter and it worked. If you would like to promote your first comment as the answer, then I'll mark it as accepted. – Stephen Avery Jul 10 '20 at 00:35

0 Answers0