Bad Request 400 when making a token request to Google gmail API - vb.net

I follow this document to make token request https://developers.google.com/identity/protocols/OAuth2InstalledApp
In the first step, it works fine. I can get the an authentication code.
In the second step, I have a problem with 400 Bad Request. I have been finding answer for this issue for 2 days, but I can't fix the problem.
I set all the properties like the document, but it doesn't matter:
POST /oauth2/v3/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&
client_id=8819981768.apps.googleusercontent.com&
client_secret=your_client_secret&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
Here is my code:
postData.Clear()
' code is the authentication code in the first request
postData.Add("code=" + code)
postData.Add("client_id=###############.apps.googleusercontent.com")
postData.Add("client_secrect=####################")
postData.Add("redirect_uri=urn:ietf:wg:oauth:2.0:oob")
postData.Add("grant_type=authorization_code")
Dim data As String = String.Join("&", postData.ToArray())
Dim request As HttpWebRequest = HttpWebRequest.Create("https://www.googleapis.com/oauth2/v3/token")
Dim byteData() As Byte = Encoding.UTF8.GetBytes(data)
request.Host = "www.googleapis.com"
request.Method = WebRequestMethods.Http.Post
request.ProtocolVersion = HttpVersion.Version11
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteData.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteData, 0, byteData.Length)
dataStream.Close()
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As Stream = response.GetResponseStream()
response.Close()
Thanks for answer !

I have just found a bug. This's a stupid bug. I typed client_secrect inteads of client_secret. I can't belive it took me 2 days to fix this error.

Related

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.

SQL access to an XL device using HTTP Post vb.net

I am currently working on a project that is supposed to pull data from an XL device to a central location. I emailed the company and they said I need to make an HTTP POST request and parse the returned JSON. Additionally they said that i should make my post request in this format.
POST /sql-request.do HTTP/1.0
Content-Length: 141
response_type=application/json&sql_statement=select sequence_number,
start_time
from timeline_stream order by sequence_number desc limit 5;
I have put what i believe to be this code into vb.net, and I get a response from the server. However it is not the requested table information. Here is the code I am currently using.
Private Sub webRequester()
Dim response As HttpWebResponse = Nothing
Dim replyStreamReader As StreamReader = Nothing
Dim request As HttpWebRequest = HttpWebRequest.CreateHttp("http://192.168.100.223/data/schema/expanded?response_type=application%2Fjson&sql_statement=select%20*%20from%20Intervals")
Dim postData As String = "test"
Dim data() As Byte = UTF8Encoding.UTF8.GetBytes(postData)
request.ContentType = "application/x-www-form-urlencoded"
request.Credentials = New NetworkCredential("User", "Pass")
request.ContentLength = data.Length
request.Method = "POST"
Using requestStream As Stream = request.GetRequestStream
requestStream.Write(data, 0, data.Length)
End Using
response = request.GetResponse()
replyStreamReader = New StreamReader(response.GetResponseStream)
Dim responseFromServer As String = replyStreamReader.ReadToEnd()
Console.WriteLine(responseFromServer)
End Sub
I have also tried using the query string as my postData, but it still returns what seems to be some default response. It is 78 pages when put in word, so here is the first line of the response I am getting.
<?xml version="1.0"?><data_schema><registers><table name="extended_user_strings" number="8" min_rows="1" max_rows="1" defined_by="system" display_name="extended_user_strings_literal" help_text="table_extended_user_strings_copy"><column name="string_1" number="1" index="no" display_name="extended_user_string_1_literal" help_text="extended_user_string_copy" type="string" access="read_write"><restrictions><max_length value="1024" /><pattern value="^[\x20-\xFE]*$" /></restrictions></column><column name="string_10" number="10" index="no" display_name="extended_user_string_10_literal" help_text="extended_user_string_copy" type="string" access="read_write"><restrictions><max_length value="1024"
How can I query the device and get the table I'm looking for?

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 Post login data httpwebrequest and cookies

im currently trying to login to my website, this works however it wont redirect when it logs in. here is my code
Dim request As WebRequest = WebRequest.Create("http://www.jamiehayles.com/test/login.php")
request.Method = "POST"
Dim postData As String = "username=testing&password=lmao1234"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
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()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
RichTextBox1.Text = responseFromServer
reader.Close()
dataStream.Close()
response.Close()
my question is, do i need cookies for it to redirect? and if so any help guys?
Take a look at what you're doing with the response from the server:
Dim responseFromServer As String = reader.ReadToEnd()
RichTextBox1.Text = responseFromServer
All you're doing is reading it and placing the content of the response into a text box. You're not actually responding to a redirect in any way.
A "redirect" means that the server responds with a specific status code and header in the response. The status code tells the browser that the response is an instruction to redirect to another resource. The header contains the new resource that the browser should request.
A web browser checks the response for this code/header and performs a new request. Your code doesn't. It just shows the response to the user, regardless of what it is.
So, to illustrate, a normal redirect happens like this:
Browser: I'm requesting this resource.
Server: Ok, I've received your request, but the resource you really want is actually over there.
Browser: Ok, then I'm now requesting that resource over there.
Server: Ok, here you go.
Your code, however, is more like this:
Code: I'm requesting this resource.
Server: Ok, I've received your request, but the resource you really want is actually over there.
Code: [no further action is taken]
The server instructed your code, in an HTTP-standard way, to request a new resource. Your code simply ignored that instruction.
You need to check the status code of the response, as well as the headers of the response, and make new requests accordingly.

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.