I'm using a third-party API and cannot get the initial authorization to work to get the session key. I've used this code with several other APIs in the past and am stumped why it's not working here. This API requires you to Base64 encode the username and password to authenticate your access.
I've tried a number of things, but narrowed down the different error messages to whether I use "Basic" or "Bearer" in my encoding.
With "Bearer" the error message is:
The remote server returned an error: (401) Unauthorized
With "Basic" the error message is:
The remote server returned an error: (500) Internal Server Error
Given the messages, I'm assuming "Bearer" is correct, because at least it's trying and is saying that the access is unauthorized... But, I'm told the username and password provided is correct! I've checked several times to verify.
Any idea what could be causing the issue?
Code:
Sub MyWebApiProcedure()
Dim vHTTPREQUEST As HttpWebRequest, vHTTPRESPONSE As HttpWebResponse, vSTREAMOBJECT As Stream, vSTREAMREADER As StreamReader, vSESSIONKEY As String
Dim vURI As String = "https://api.myapi.com/api/myendpoint/"
Dim vUSERNAME As String = "myusername"
Dim vPASSWORD As String = "mypassword"
Dim vTOKEN As String = "Bearer " + System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(vUSERNAME + ":" + vPASSWORD))
vHTTPREQUEST = CType(WebRequest.Create(vURI), HttpWebRequest)
vHTTPREQUEST.Method = "GET"
vHTTPREQUEST.ContentType = "application/x-www-form-urlencoded"
vHTTPREQUEST.Accept = "application/json"
vHTTPREQUEST.Headers.Add("Authorization", vTOKEN)
'>>> THE ERROR OCCURS AT THIS LINE <<<'
vHTTPRESPONSE = CType(vHTTPREQUEST.GetResponse(), HttpWebResponse)
vSTREAMOBJECT = vHTTPRESPONSE.GetResponseStream()
vSTREAMREADER = New StreamReader(vSTREAMOBJECT, Text.Encoding.UTF8)
vSESSIONKEY = vSTREAMREADER.ReadToEnd()
vHTTPRESPONSE.Close()
vSTREAMREADER.Close()
Response.Write(vSESSIONKEY)
End Sub
EDIT: Received the Python version from the support team based on the documentation.
encoded_auth_text = base64.b64encode(b'username' + b':' + b'password')
response = requests.post(url='https://api.myapi.com/api/myendpoint', headers={'Authorization': encoded_auth_text}, timeout=30)