Why am I getting the 400 error (Bad request) - vb.net

After receiving the authorization code from Google Api, I try to make a request to retrieve the user's data, but the 400 error always occurs.
Dim objSerializer = New JavaScriptSerializer()
Dim objContent = New NameValueCollection()
Dim strClientId = "****.apps.googleusercontent.com"
Dim strClientSecret = "****"
Dim strTokenUri = "https://accounts.google.com/o/oauth2/token"
Dim objClient = New WebClient()
objClient.Encoding = Encoding.UTF8
objClient.QueryString.Add("code", strCode)
objClient.QueryString.Add("client_id", strClientId)
objClient.QueryString.Add("client_secret", strClientSecret)
objClient.QueryString.Add("redirect_uri", "http://localhost:38815/Info.aspx")
objClient.QueryString.Add("grant_type", "authorization_code")
Dim data = objClient.UploadValues(strTokenUri, "POST", objClient.QueryString)
Dim objResponse As String = Encoding.UTF8.GetString(data)
Dim objGoogleJwtToken = objSerializer.Deserialize(Of GoogleAccessToken)(objResponse)
Error:
System.Net.WebException: The remote server returned an error: (400) Request Incorrect.
UPDATE
This is my post data
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
code=4%2FewGRFvsrdTHGF698QFq6d359KAPRWc4c-8ipKjJU58X1uk14WNc5uRw45N-c88HtbWkL17wEfLlasdfGRSU&
client_id=****.apps.googleusercontent.com&
client_secret=****&
redirect_uri=http%3A%2F%2Flocalhost%3A38815%2FInfo.aspx&
grant_type=authorization_code
I receive the following json result:
{
"error": "invalid_grant",
"error_description": "Bad Request"
}

After some tests I found another error that is related to the following topic:
https://github.com/morgoth/picasa/issues/39
Even correcting the redirect_uri parameter was still not getting the authenticated token, so I used the Http client for .NET Restsharp and got the following solution that worked:
Private Shared Function GetAccessToken3(ByVal strCode As String, ByVal strClientId As String, ByVal strClientSecret As String, ByVal strTokenUri As String) As GoogleAccessToken
Dim objClient As RestClient
Dim objIResponse As IRestResponse
Dim objRequest As RestRequest
Dim objSerializer As New DataContractJsonSerializer(GetType(GoogleAccessToken))
Dim objResponse As GoogleAccessToken
objClient = New RestClient(strTokenUri)
objClient.Authenticator = New HttpBasicAuthenticator(strClientId, strClientSecret)
objRequest = New RestRequest(Method.POST)
objRequest.AddHeader("Content-Type", "application/x-www-form-urlencoded")
objRequest.AddHeader("Accept", "application/json")
objRequest.AddParameter("code", strCode, ParameterType.GetOrPost)
objRequest.AddParameter("client_id", strClientId, ParameterType.GetOrPost)
objRequest.AddParameter("client_secret", strClientSecret, ParameterType.GetOrPost)
objRequest.AddParameter("redirect_uri", "http://localhost:38815/Default.aspx", ParameterType.GetOrPost)
objRequest.AddParameter("grant_type", "authorization_code", ParameterType.GetOrPost)
objIResponse = objClient.Execute(objRequest)
If objIResponse.StatusCode <> HttpStatusCode.OK OrElse objIResponse.ErrorException IsNot Nothing Then
Throw New Exception("Error: " + objIResponse.StatusCode)
End If
objResponse = DirectCast(objSerializer.ReadObject(New MemoryStream(Encoding.UTF8.GetBytes(objIResponse.Content))), GoogleAccessToken)
Return objResponse
End Function
I'm validate token result in JWT Tool

Related

The remote server returned an error: (415) Unsupported Media Type Vb dot net

I am facing the issue in one of my vb dot net application while posting the values to web api method.
My code:
Dim uri As String = "http://server/api/TMS/CreateIndent"
Dim request As Net.HttpWebRequest = Net.HttpWebRequest.Create(uri)
Dim headers As WebHeaderCollection = New WebHeaderCollection()
Dim tokenurl As String = Token
request.ContentType = "multipart/form-data"
request.Method = "POST"
headers.Add("Token", tokenurl)
headers.Add("NTID", "abcdef")
request.Headers = headers
Dim value As String = "[{""PurposeId"" : ""4"",""MitraIndentId"": ""558"",""Employee"":{""NTID"": ""abcdedf""},""Purposeothers"": ""null"", ""TravellingDetails"":[{""ModeOfTravelID"": ""4"",""DepartureDate"":""01/02/2022 16:23"",""DepartedFrom"":""TD1"",""ArrivalDate"":""02/02/2022 16:24"",""ArrivalAt"":""TD2"",""BoschCost"":""123"",""EmployeeCost"":""500"",""IsSupportDocumnentAvailable"":""true"",""DeviationKey"":""1644404033300""}]}]"
Dim array(1) As Char
array(0) = "["
array(1) = " "
Dim value1 As String = value.Remove(value.Length - 1)
Dim value2 As String = value1.TrimStart(array)
Dim keyparameter = New Dictionary(Of String, Object) From {
{"Expense", value2}}
Dim PostString As String = JsonConvert.SerializeObject(keyparameter)
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(PostString)
request.ContentLength = byteArray.Length
Dim dataStream As IO.Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close() 'sends request
Dim myResp As HttpWebResponse = request.GetResponse()
While getting the response, I am getting the issue.
Error: The remote server returned an error: (415) Unsupported Media Type
But if i use the same json string in postman, its working fine.
Postman code:
POST //api/TMS/CreateIndent HTTP/1.1
Host:
Token: sZnYPDJE454wx7m3FMNvTFe5k6fATnKUgUE3toV5MEgB8ydfni
NTID: abcdefg
Cache-Control: no-cache
Postman-Token: 44836019-b3d4-c143-3c1f-5dbff2834584
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="Expense"
{"PurposeId" : "4","MitraIndentId": "558","Employee":{"NTID": "abcdefg"},"Purposeothers": "null", "TravellingDetails":[{"ModeOfTravelID": "4","DepartureDate":"01/02/2022 16:23","DepartedFrom":"TD1","ArrivalDate":"02/02/2022 16:24","ArrivalAt":"TD2","BoschCost":"123","EmployeeCost":"500","IsSupportDocumnentAvailable":"true","DeviationKey":"1644404033300"}]}
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Please help me to resolve this issue.
Thanks in advance

RestSharp response forbidden

I trying get a simple request to https://c-cex.com/t/prices.json
If i use this url in browser the correct response is showed , but if i make the same request using RestRequest i receive the 403 error Forbidden in all times. i trying HttpClient,WebRequest i get the same error
I put the header with user-agent, no cache and a lot of another values but did not work
Any ideas about this problem?
Dim url As String = "https://c-cex.com/t/prices.json"
Dim client As New RestSharp.RestClient(url)
Dim request = New RestRequest(url, Method.GET)
Dim response = client.Execute(request)
Updated code with apisign request
Dim nonce As String = CInt((DateTime.UtcNow - New DateTime(1970, 1, 1)).TotalSeconds).ToString
Dim url As String = "https://c-cex.com/t/api.html?a=getbalance&currency=BTC&apikey=" & API_KEY & "&nonce=" & nonce
Dim keybytes() = UnicodeEncoding.ASCII.GetBytes(API_SECRET)
Dim hs As System.Security.Cryptography.HMACSHA512 = New System.Security.Cryptography.HMACSHA512(keybytes)
Dim urlbytes() = UnicodeEncoding.ASCII.GetBytes(url)
Dim sh() = hs.ComputeHash(urlbytes)
Dim client As New RestSharp.RestClient(url)
Dim request = New RestRequest(url, Method.GET)
request.AddHeader("Cache-Control", "no-cache")
request.AddHeader("apisign", HttpUtility.UrlEncode(ToHexString(sh)))
Dim response = client.Execute(request)
I am getting the response without providing the header information and It looks given piece of code is working correctly for me in VB and C#.As a best practice, base URL needs to be specified in RestClient and relative URL in RestRequest.
Please recheck without adding the request header information
VB:
Imports RestSharp
Module Module1
Sub Main()
Dim host As String = "https://c-cex.com"
Dim endpoit As String = "t/prices.json"
Dim client As New RestSharp.RestClient(host)
Dim request = New RestRequest(endpoit, Method.GET)
Dim response = client.Execute(request)
Console.WriteLine("Response Body " + response.Content)
Console.WriteLine("Response Code " + response.StatusDescription)
End Sub
End Module
C#:
String host = "https://c-cex.com";
String endpoint = "t/prices.json";
RestClient _restClient = new RestClient(host);
var request = new RestRequest(endpoint, Method.GET);
var response = _restClient.Execute(request);
Console.WriteLine("Response Body :"+response.Content);
Console.WriteLine("Response Status Code :" + response.StatusDescription);

call http get using proxy

How can I edit the code to accept proxy?
CallHttp functions
Public Shared Function CallHttp(ByVal url As String, _
ByVal params As String, _
ByVal httpPost As Boolean) As String
If httpPost Then
Return CallHttpPost(url, params)
Else
Return CallHttpGet(url, params)
End If
End Function
CallHttpPost function:
Protected Shared Function CallHttpPost(ByVal url As String, _
ByVal params As String) As String
Dim loHttp As HttpWebRequest
'params = QueryStringEncode(params, TypeEncodeEnum.urlEncode)
loHttp = CType(WebRequest.Create(url), HttpWebRequest)
loHttp.Method = "POST"
Dim requestWriter As StreamWriter = New StreamWriter(loHttp.GetRequestStream())
If Not String.IsNullOrEmpty(params) Then
requestWriter.Write(params)
End If
requestWriter.Close()
loHttp.ContentType = "application/x-www-form-urlencoded"
loHttp.Headers.Set("Pragma", "no-cache")
loHttp.AllowAutoRedirect = True
loHttp.KeepAlive = True
loHttp.Timeout = 30 * 1000
'loHttp.Referer = url
Dim loWebResponse As HttpWebResponse = CType(loHttp.GetResponse(), HttpWebResponse)
Dim enc As Encoding = System.Text.Encoding.UTF8
Dim loResponseStream As StreamReader = New StreamReader(loWebResponse.GetResponseStream(), enc)
Dim lcHtml As String = loResponseStream.ReadToEnd()
loWebResponse.Close()
loResponseStream.Close()
Return lcHtml
End Function
Im behind a corporate firewall and I get a 407 proxy authentication required error if I use the function like this
strXML = CallHttp(API_URL, sb.ToString, False)
any ideas?
user and pass are the authentication of your proxy
Dim myProxy As New WebProxy("192.168.1.2:8080")
Dim authentication As New System.Net.NetworkCredential("user", "pwd")
myProxy.Credentials = authentication
Dim loHttp As HttpWebRequest
loHttp .Proxy = myProxy

Google OAuth Token error - 400 Bad Request

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

How to log into router with HttpWebRequest?

I'm trying to figure out how to successfully log into a DSL-Router (Model: Speedport w504v Type A).
I wrote a function usinig HttpWebRequest and HttpWebResponse. So far this function is not finished and is only for finding out the right login process.
Public Function DoRequest(ByVal url As String, ByVal password As String, ByVal container As CookieContainer) As String
'Login Request
Dim reqLogin As HttpWebRequest = DirectCast(HttpWebRequest.Create("https://speedport.ip/cgi-bin/login.cgi"), HttpWebRequest)
reqLogin.CookieContainer = container
reqLogin.Method = "POST"
reqLogin.Referer = "https://speedport.ip/hcti_start_passwort.stm"
reqLogin.KeepAlive = True
reqLogin.Host = "speedport.ip"
reqLogin.ContentType = "application/x-www-form-urlencoded"
reqLogin.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
reqLogin.Headers.Add("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3")
reqLogin.Headers.Add("Accept-Encoding", "gzip, deflate")
'Login Data
Dim encoding As New ASCIIEncoding()
Dim data As String = Uri.EscapeDataString("pws") & "=" & Uri.EscapeDataString(password)
Dim bytes As Byte() = encoding.GetBytes(data)
reqLogin.ContentLength = bytes.Length
Dim stream As Stream = reqLogin.GetRequestStream
stream.Write(bytes, 0, bytes.Length)
stream.Close()
'Login Response
Dim resLogin As HttpWebResponse = DirectCast(reqLogin.GetResponse(), HttpWebResponse)
'Receive Cookie
Dim CookieHeaderValue As String = reqLogin.Headers.Get("Cookie")
If CookieHeaderValue <> Nothing Then
Dim aCookie As String() = CookieHeaderValue.Split("=")
Dim Cookie As New Cookie
Cookie.Domain = "speedport.ip"
Cookie.Path = "/"
Cookie.Secure = True
Cookie.Name = aCookie(0)
Cookie.Value = aCookie(1)
container.Add(Cookie)
End If
'Url Request
Dim reqIndex As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
reqIndex.CookieContainer = container
reqIndex.Method = "GET"
reqIndex.Referer = "https://speedport.ip/wait_login.stm"
reqIndex.KeepAlive = True
reqIndex.Host = "speedport.ip"
reqIndex.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
'Url Content
Dim resIndex As HttpWebResponse = DirectCast(reqIndex.GetResponse(), HttpWebResponse)
Dim sr As StreamReader = New StreamReader(resIndex.GetResponseStream())
Dim output As String = sr.ReadToEnd
resIndex.Close()
Return output
End Function
Unfortunately I don't get the right content. Instead I'm getting the sitecontent from an Error-Page saying:
double administration access!
This site is returned when you try to login but there is another session already running.
So maybe I'm already successfully logged in but don't get the site content.
I get the header information from an Firefox AddOn called HTTP Live Header.
I also tried to run curl but also did not work:
curl -d "pws=PASSWORD" -c cookies.txt -e https://speedport.ip/hcti_start_passwort.stm -k https://speedport.ip/cgi-bin/login.cgi
curl -c cookies.txt -e https://speedport.ip/wait_login.stm -k https://speedport.ip/index.stm
Maybe someone has an idea what's going wrong.
Using Fiddler I figured it out. I've to set also the User Agent Header for the first request.
reqLogin.UserAgent = "YOUR USERAGNET STRING"
Furthermore I don't have to get the value for reqLogin.Headers.Get("Cookie").
It's already set to the CookieContainer so cancel the "Receive Cookie" part.