Google OAuth Token error - 400 Bad Request - vb.net

I'm trying to authenticate my application using OAuth2 and using the 'installed applications' flow (get auth-code and then request token). I'm getting a 400 bad request error when requesting the token on the GetResponse() line. My code is as follows:
Public Sub New()
Dim tokenRequest As WebRequest =
WebRequest.Create("https://accounts.google.com/o/oauth2/token")
Dim requestString As String = "code=<auth-code>" _
& "&client_id=<client_id>" _
& "&client_secret=<client_secret>" _
& "&redirect_uri=http://localhost" _
& "&grant_type=authorization_code"
byteArray = StrToByteArray(System.Web.HttpUtility.UrlEncode(requestString))
tokenRequest.Credentials = CredentialCache.DefaultCredentials
tokenRequest.Method = "POST"
tokenRequest.ContentLength = byteArray.Length
tokenRequest.ContentType = "application/x-www-form-urlencoded"
Dim dataStream As Stream = tokenRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Console.WriteLine("Getting response...")
'Get response
Try
Dim response As WebResponse = tokenRequest.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
Dim data As Stream = response.GetResponseStream
Array.Resize(byteArray, 4096)
Array.Clear(byteArray, 0, byteArray.Length)
data.Read(byteArray, 0, byteArray.Length)
response.Close()
Catch wex As WebException
Console.WriteLine("ERROR! : ")
Console.WriteLine(wex.Message)
Console.WriteLine(wex.Status)
Console.WriteLine(wex.Data)
Console.WriteLine(wex.InnerException.Message)
Console.WriteLine(wex.HelpLink)
End Try
End Sub
The specifics of the error are below:
The remote server returned an error: (400) Bad Request.
7
System.Collections.ListDictionaryInternal
System.NullReferenceException: Object reference not set to an instance of an obj
ect.
at GADownload.GoogleAnalytics..ctor() in ***.vb:line 86
at GADownload.Main1.Main(String[] args) in ****.vb:line 18
I've had a look at Google GetAccessToken : Bad Request 400 and Google GData .Net OAuthUtil.GetAccessToken 400 Bad Request but have not found a solution suited to this code. I have already checked all the solutions suggested and implemented them, but with no luck so far.

looks like you are not setting values for the parameters auth-code, client_id or client_secret.
you can debug these parameters with a curl command to see if this is the source of the problem. e.g.
curl -X POST -d "code=<auth-code>&client_id=<client_id>&client_secret=<client_secret>"&grant_type=authorization_code" http://localhost:8000/auth/token

Can you try URL encoding redirect_uri
redirect_uri=http://localhost
That is the only thing I'm seeing on your code vs. mine. Here's my code that is similar in vb and working
Dim sb As New StringBuilder
sb.Append("code=").Append(Request.QueryString("code")) _
.Append("&client_id=") _
.Append(Session.Item("ClientID")) _
.Append("&client_secret=") _
.Append(Session.Item("ClientSecret")) _
.Append("&redirect_uri=") _
.Append(HttpUtility.UrlEncode("http://localhost/1.aspx")) _
.Append("&grant_type=authorization_code")
Dim requestGoogle As HttpWebRequest =
WebRequest.Create("https://accounts.google.com/o/oauth2/token")
requestGoogle.Method = "POST"
requestGoogle.ContentType = "application/x-www-form-urlencoded"
requestGoogle.ContentLength = sb.Length
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(sb.ToString)
sb.Clear()
requestGoogle.GetRequestStream.Write(byteArray, 0, byteArray.Length)
byteArray = Nothing
Dim responseGoogle As HttpWebResponse = requestGoogle.GetResponse()
If responseGoogle.StatusCode = HttpStatusCode.OK Then
Dim sr As StreamReader = _
New StreamReader(responseGoogle.GetResponseStream)
Dim s As String = sr.ReadToEnd
sr.Close()
responseGoogle.GetResponseStream.Close()
requestGoogle.GetRequestStream.Close()
'Response.Write(s)
End If

Related

VB.NET ~ PUT WebRequest raising exceptions when trying to GetResponse of it

I am getting TWO exceptions. The first one in the regular code and the second into the exception handling block.
I have this function (below) that supposed to change user settings in a Web API using PUT method. Everything runs fine until the point that I try to get a response from the web request. Then it raises the first exception (unknown) and when I try to handle the error I get a second exception "Object reference not set to an instance of an object".
As far as I know normally what will cause this error is the attempt of getting a response of an unassigned web request, but in this case it IS assigned and the Uri is valid. All the credentials for authorization are correct too.
This is my code:
Try
Dim webRequest As System.Net.HttpWebRequest
webRequest = System.Net.HttpWebRequest.Create(InternalSettings.APIurl + "/config")
webRequest.Headers("Authorization") = InternalSettings.APIpwd
webRequest.Headers("API-Application-Key") = InternalSettings.APIkey
webRequest.Method = "PUT"
webRequest.ContentType = "application/x-www-form-urlencoded"
Dim postData As String = ""
postData += "SaveAllCustomersData=false"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
'The next line will raise an unknown exception
Dim myHttpWebResponse As HttpWebResponse = webRequest.GetResponse
Dim responseReader As StreamReader = New StreamReader(myHttpWebResponse.GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest.GetResponse().Close()
Catch ex As WebException
'The next line will raise a "Object reference not set to an instance of an object" exception
Dim resp = New StreamReader(ex.Response.GetResponseStream()).ReadToEnd()
Dim obj = JsonConvert.DeserializeObject(resp)
Return False
End Try
If you are using basic authentification you can try something like this:
Dim strUrl As String = InternalSettings.APIurl + "/config"
Dim request As WebRequest = DirectCast(WebRequest.Create(strUrl), HttpWebRequest)
Dim strResponse As String = ""
Dim byteAuth() As Byte = Encoding.UTF8.GetBytes(InternalSettings.APIkey & ":" & InternalSettings.APIpwd)
Dim strPost As String = "SaveAllCustomersData=false"
Dim bytePost() As Byte = Encoding.UTF8.GetBytes(strPost)
request.ContentType = "application/x-www-form-urlencoded"
request.Method = "PUT"
request.Headers.Add("Authorization", "Basic " & Convert.ToBase64String(byteAuth))
Using sw = New StreamWriter(request.GetRequestStream())
sw.Write(bytePost, 0, bytePost.Length)
sw.Flush()
Using response As HttpWebResponse = request.GetResponse()
Using sr = New StreamReader(response.GetResponseStream())
strResponse = sr.ReadToEnd()
End Using
End Using
End Using

Can we call JSON POST API from VB.NET Windows App?

Here I am always getting "The remote server returned an error: (500) Internal Server Error.". Even the API is correct and working nicely through POSTMAN and in other languages also. Please guide me so solve this issue. I am attaching the function which is calling the API directly.
Private Function SendRequest() As String
Dim response As String
Dim request As WebRequest
Dim encoding As New System.Text.ASCIIEncoding
Dim uri = ""
Dim Tran = "15"
Dim Amount As Integer = 1000
Dim ReferenceID = "015bfa15-15ec-4dc7-903c-053ffacb6688"
Dim POS = "57290070"
Dim Store = "RESTSIM00000001"
Dim Chain = "J#P-Reg"
Dim JSONString = "{""tran"":""" & Tran & """,""amount"":""" & Amount & """,""reference"":""" & ReferenceID & """,""pos"":""" & POS & """,""store"":""" & Store & """,""chain"":""" & Chain & """}"
Dim jsonDataBytes() As Byte = encoding.GetBytes(JsonConvert.SerializeObject(JSONString))
request = WebRequest.Create(uri)
request.ContentLength = jsonDataBytes.Length
request.ContentType = "application/json"
request.Method = "POST"
Using requestStream = request.GetRequestStream
requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
requestStream.Close()
Using responseStream = request.GetResponse.GetResponseStream
Using reader As New StreamReader(responseStream)
response = reader.ReadToEnd()
End Using
End Using
End Using
Return response
End Function

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?

Error trying to Create ASANA Project in VB.NET

I am getting an error:
400 Bad request
when trying to create a project via vb.net in asana.
Note: The ApiKey I am using works when I use it in other vb.net code to get the list of workspaces which is where I got my workspace ID.
Here is my code; I would be grateful for any insight...
Public Sub main()
Dim address As Uri
address = New Uri("https://app.asana.com/api/1.0/projects")
Dim ApiKey As String
ApiKey = "<my api key>"
Dim basicAuthenticationString As String
basicAuthenticationString = Convert.ToBase64String(New UTF8Encoding().GetBytes(ApiKey + ":"))
' Create the web request
Dim request As HttpWebRequest
request = DirectCast(WebRequest.Create(address), HttpWebRequest)
request.Headers("Authorization") = "Basic " & basicAuthenticationString
request.Method = "POST"
request.ContentType = "application/json"
Dim postData As String = "{""data"":[{""name"":""Randy Test Project"",""notes"":""Randy Test Project Notes"",""workspace"":5272875888767}]}"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As HttpWebResponse = request.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Console.WriteLine(responseFromServer)
reader.Close()
dataStream.Close()
response.Close()
Exit Sub
End Sub
I was able to figure it out, My address needed to be:
Dim address As Uri = New Uri("app.asana.com/api/1.0/teams/22956925957833/projects")
Then my postData needed to be:
Dim postData As String = "{""data"":{""name"":""Randy Test Project"",""notes"":""Randy Test Project Notes""}}"
Alternatively, you can specify the team or workspace in the post data. When you get a 400 Bad Request the body of the error response will tell you which fields were actually missing/invalid.

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.