VB.NET 401 Unauthorized error in PayPal OAuth API - vb.net

I'm trying to get an access token back from PayPals OAuth API, I can get it back with curl but need to get the code through vb.NET. I always get a 401 unauthorized response but can't see why. I'm using the following code:
Dim uri as new Uri("https://api-m.sandbox.paypal.com/v1/oauth2/token")
Dim wClientID As String = "client ID"
Dim wClientSecret As String = "Client Secret"
Dim data as string = "grant_type=client_credentials"
Dim dataByte as Byte()
ServicePointManager.Expect100Continue = true
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
request = WebRequest.Create(uri)
request.Headers.Add("Username", wClientID)
request.Headers.Add("Password", wClientSecret)
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " & wClientID & ":" & wClientSecret)
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "POST"
dataByte = Encoding.UTF8.GetBytes(data)
Using requestStream = request.GetRequestStream
requestStream.Write(dataByte, 0, dataByte.Length)
requestStream.Close()
End Using
Any help would be appreciated, I've triple checked the client id and secret, both are definitely correct

You need to Base64 encode the clientid:secret string for HTTP basic authentication. Curl does this for you.

Related

WebRequest with Bearer Authorization in VB.NET

I would need to send a POST request to a remote server, which requires a Bearer Authorization.
this is my VB.NET code:
Public Shared Function syncAsana() As String
Dim result As String
Try
Dim token As String = "TOKEN"
Dim uri As String = "https://URL/api/1.0/tasks"
Dim postData As String = "assignee=email&notes=TEST_NOTES&name=NOME 1&projects=123985"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim request As WebRequest = WebRequest.Create(uri)
request.Method = "POST"
request.PreAuthenticate = True
request.Headers.Add("Authorization", "Bearer " & token)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
Using dataStream1 As Stream = response.GetResponseStream()
................
result = responseFromServer
End Using
response.Close()
Catch ex As Exception
result = ex.Message
End Try
Return result
End Function
the problem is that I always get the error The underlying connection was closed: An unexpected error occurred on a receive
the same request made with jquery / ajax or with curl works.
I have tried both from the local server launched by visual studio, and by putting the code on the production server.
could you tell me where i'm wrong?

Can't make BigCommerce API call in VB.NET

I get
'underlying connection was closed'
when running the code below. I am using vb.net 2012 (I must use this version) with the RestSharp library and am trying to retrieve product data from a bigcommerce.com store. This is a simple vb.net 2012 console program that once I get working I can build upon. I have tried changing around the code somewhat even making certain things redundant like the method and URL but I can't get it to work.
Dim client As New RestClient
client.BaseUrl = New Uri("https://api.bigcommerce.com/stores/mystorehash/v3/catalog/products")
Dim request As New RestRequest("https://api.bigcommerce.com/stores/mystorehash/v3/catalog/products", Method.GET)
request.AddHeader("Accept", "application/json")
request.AddHeader("Content-Type", "application/json")
request.AddHeader("X-Auth-Client", "notactualvaluenotactualvalue")
request.AddHeader("X-Auth-Token", "notactualvaluenotactualvalue")
request.Method = Method.GET
Dim response As New RestResponse
response = client.ExecuteAsGet(request, Method.GET)
Console.WriteLine("response.Content=" & response.Content)
Console.WriteLine("response.ErrorMessage=" & response.ErrorMessage)
Console.WriteLine("response.ResponseStatus=" & response.ResponseStatus)
Console.WriteLine("response.IsSuccessful=" & response.IsSuccessful)
Console.WriteLine("response.Headers.Count=" & response.Headers.Count)
Output:
Any help would be appreciated, hopefully I'm doing something stupid that can be easily fixed
For anyone else that finds this the full implementation of Nathan Booker's suggestion is below. When you attempt to access the Big Commerce api in a VB.NET application you need to specify TLS 1.2. If you don't you'll recieve an HTTP status of 502 - System.IO.IOException Authentication failed because the remote party has closed the transport stream. The solve is done like:
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
ServicePointManager.DefaultConnectionLimit = 9999
Dim request As HttpWebRequest = CType(WebRequest.Create("https://api.bigcommerce.com/stores/<Redacted>/v3/catalog/products"), HttpWebRequest)
request.AllowAutoRedirect = True
request.ContentType = "application/json"
request.Accept = "application/json"
request.Method = "GET"
request.Headers.Add("X-Auth-Client", "<Redacted>")
request.Headers.Add("X-Auth-Token", "<Redacted>")
Dim response As WebResponse = request.GetResponse()
Diagnostics.Debug.WriteLine((CType(response, HttpWebResponse)).StatusDescription)
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As StreamReader = New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Diagnostics.Debug.WriteLine(responseFromServer)
reader.Close()
response.Close()
This may be related to your HTTP version or (more likely) SSL/TLS protocol.
If possible, please make sure you're using HTTP 1.1 and TLS 1.2.

Trouble with POSTing JSON to endpoint

I'm trying to submit a POST request containing JSON to a given endpoint. However the below code sends me to a login page which is the default functionality for all non-/api endpoints. Because Postman doesn't direct me to the login page but correctly hits the API, I'm assuming the problem is in this C# code.
Dim RemoteUrl As String = "https://my-site.com/api/tournament/results"
Dim result As String = ""
Dim xmlHttpReq As HttpWebRequest = CType(WebRequest.Create(RemoteUrl), HttpWebRequest)
xmlHttpReq.Method = "POST"
xmlHttpReq.ContentType = "application/json"
With (New StreamWriter(xmlHttpReq.GetRequestStream))
.Write(Json)
.Flush()
.Close()
Dim httpResponse As HttpWebResponse = CType(xmlHttpReq.GetResponse(), HttpWebResponse)
With (New StreamReader(httpResponse.GetResponseStream))
result = .ReadToEnd
End With
End With
Any idea what steps I need to take to debug this?

Bearer token in the (OAuth) Authorization request header for REST API POST call

Hey all i am trying to figure out how to do this OAuth authorization token for a REST API POST call.
The documents state:
With a valid access token, your app can make calls to any Yammer API endpoint by sending the access token as a “Bearer” token in the “Authorization” request header.
GET /api/v1/messages/following.json HTTP/1.1
Host: www.yammer.com
Authorization: Bearer abcDefGhiFor
more details on the “Bearer” token refer to [enter link description here][1]
If the access token expires or the user de-authorizes your app, the API request will return an HTTP 401 with the following error in the body of the response.
{
"response": {
"message": "Token not found.",
"code": 16,
"stat": "fail"
}
}
Your app can request a new access token by re-running the appropriate flow if this error occurs.
Currently my VB.net code is this:
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
Dim address As Uri
Dim data As StringBuilder
Dim byteData() As Byte
Dim postStream As Stream = Nothing
address = New Uri("https://www.yammer.com/api/v1/messages.json")
request = DirectCast(WebRequest.Create(address), HttpWebRequest)
request.Method = "POST"
request.Headers("Authorization") = "Bearer " & yammerAPI.userToken
request.ContentType = "application/json"
request.Host = "www.yammer.com"
Dim body As String = "test"
Dim replied_to_id As Integer = 123456789
Dim group_id As Integer = 123456789
data = New StringBuilder()
'data.Append("&replied_to_id=" & HttpUtility.UrlEncode(replied_to_id))
data.Append("group_id=" & HttpUtility.UrlEncode(group_id))
data.Append("&body=" & HttpUtility.UrlEncode(body))
byteData = UTF8Encoding.UTF8.GetBytes(data.ToString())
request.ContentLength = byteData.Length
Try
postStream = request.GetRequestStream()
postStream.Write(byteData, 0, byteData.Length)
Finally
If Not postStream Is Nothing Then postStream.Close()
End Try
Try
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Debug.Print(reader.ReadToEnd())
Finally
If Not response Is Nothing Then response.Close()
End Try
I keep getting an error of: The remote server returned an error: (401) Unauthorized.
I found this in a following Stackoverflow posting:
The Yammer API requires the OAuth data to be in the header. If you look at their example for Getting Data, you'll see the request looks like.
GET /api/v1/messages/favorites_of/1234 HTTP/1.1
HOST: www.yammer.com
Authorization: OAuth oauth_consumer_key="KsTROcNF1Fx3e1PwA",oauth_token="vlVH7A7DOm9wXuHdv58A",oauth_signature_method="PLAINTEXT",oauth_timestamp="1297383841092",oauth_nonce="1047685618",oauth_verifier="E4F8",oauth_signature="yPsEvDnNPIA8xGCFLvMJ73K0DD9ivMpATJeFOSo%26fSFh9UPkHQ6oRwK5OTne33ltnSnbQ9XrAhA72heg"
The OAuth data is in the Authorization header and not in the URL. The only time you have any OAuth data in the URL is when you do the authorize.
Any help would be great to understand this more!
My recent experience with Oauth suggests the content type should be:
Request.ContentType = "application/x-www-form-urlencoded"
Request.Method = "POST"
Request.ContentLength = byteArray.Length
rather than request.ContentType = "application/json"

VB.NET - How To Make a Post to Blogspot Using Blogger API V3?

I'm trying to to make a new post through my vb.net application using blogger api.
But I'm fail every time.
Sometimes it's return 403 forbidden error some times Unauthorised error.
Please Help.
Dim mBlogID As String = "5861877551002158183"
Dim AuthToken As String = "AIza......xxxx..........E6g"
Dim post As String = "{""kind"": ""blogger#post"", ""blog"": { ""id"": """ & mBlogID & """}, ""title"": ""abc-title"", ""content"": ""abc-cont""}"
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://www.googleapis.com/blogger/v3/blogs/" & mBlogID & "/posts?key=" & AuthToken), HttpWebRequest)
request.Method = "POST"
request.ContentLength = post.Length
request.ContentType = "application/json"
request.Headers.Add("Authorization: ", AuthToken) '<--- error here
Using requestStream As Stream = request.GetRequestStream()
Dim postBuffer As Byte() = Encoding.ASCII.GetBytes(post)
requestStream.Write(postBuffer, 0, postBuffer.Length)
End Using
Using response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse) '<--- Unauthorised error or 403 error here
Using responseStream As Stream = response.GetResponseStream()
Using responseReader As New StreamReader(responseStream)
'Dim json As String = responseReader.ReadToEnd()
'Dim PostURL As String = Regex.Match(json, """url"": ?""(?<id>.+)""").Groups("id").Value
MsgBox(json) 'want to read json response here.
'MsgBox(PostURL)
End Using
End Using
End Using
This code return this error :Specified value has invalid HTTP Header characters.
Parameter name: name
can anybody fix it? I just want to make a new post to blogger and read its URL.
Project Information:-
Platform: Visual Basic 2010
Blogger API Version: V3
I Suggest view this solution. The post has fully explanations.