response : unauthorized in Swagger via RestSharp - vb.net

I need to use an API from Swagger that sends email but I am having a problem in authorization I passed the token but still the result is Unauthorized.
I use the code below.
`Dim url = "test123/test.com" (can't include the actual)
Dim apiKey = "12312"
Dim apiPassword = "12312"
Dim client = New RestClient(url)
Dim request = New RestRequest("token", Method.POST)
request.Parameters.Clear()
request.AddParameter("grant_type", "password")
request.AddParameter("username", apiKey)
request.AddParameter("password", apiPassword)
Dim response As IRestResponse = client.Execute(request)
_pristrKey = response.Content
Return JsonConvert.DeserializeObject(response.Content)`
Now I have the Token in _pristrKey
Then I do this for email sending.
`Dim url = "test123/test.com"
Dim client = New RestClient(url)
Dim request = New RestRequest("api/email", Method.POST)
request.Parameters.Clear()
request.AddHeader("accept", "application/json")
request.AddParameter("Authorization", String.Format($"Bearer " +
_pristrKey), ParameterType.HttpHeader)
request.AddHeader("Content-Type", "application/json")
Dim apiInput = New With {Key .bulkId = "123", Key .from =
"test123#gmail.com", Key .subject = "Test", Key .text = "Test123", Key
.to = "test321#gmail.com"}
request.AddParameter("application/json",
JsonConvert.SerializeObject(apiInput), ParameterType.RequestBody)
request.RequestFormat = DataFormat.Json
Dim response As IRestResponse = client.Execute(request)`
Actual Output: response = "StatusCode: Unauthorized, Content-Type: , Content-Length: 0)"

This error happens because your token is invalid check your token if you got it right, also check for extra double quote(") in the token. I have encounter this in vb.net just use:
.Replace("""", "").Trim()

Related

Get a token from a rest api with vbnet. Method POST

I am trying to get a token from a ws but so far I have not succeeded.
From postman if I get the token but from my vbnet application no.
The code I use in vbnet is:
Dim client = New RestClient("https://xxxxxxxx.com/IntegrationAPI_2/api/login")
Dim request2 = New RestRequest(Method.POST)
request2.AddParameter("application/json", ParameterType.RequestBody)
request2.RequestFormat = DataFormat.Json
request2.AddParameter("Username", UserVar)
request2.AddParameter("Password", PasswVar)
Dim response2 As RestResponse = client.Execute(request2)
The result obtained in vbnet in statuscode is 0, but in postman it is 200 ok
I am programming in visual studio 2015. Thanks
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls
URLSERVICE += "?username=" & User & "&password=" & Passw
Dim client = New RestClient("" & URLSERVICE & "")
Dim request = New RestRequest(Method.POST)
request.AddHeader("Content-Type", "application/json")
request.RequestFormat = DataFormat.Json
Dim response As RestResponse = client.Execute(request)

Why am I getting the 400 error (Bad request)

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

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);

Implement bittrex API in VB.NET

As per Bittrex API Docs it says they use a standard HMAC-SHA512 signing. Append apikey and nonce to your request and calculate the HMAC hash and include it under an apisign header. Note: the nonce is not respected right now but will be enforced later.
$apikey='xxx';
$apisecret='xxx';
$nonce=time();
$uri='https://bittrex.com/api/v1.1/market/getopenorders?apikey='.$apikey.'&nonce='.$nonce;
$sign=hash_hmac('sha512',$uri,$apisecret);
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult);
DEPRECATING
Request:
https://bittrex.com/api/v1.1/account/getbalances?apikey=apikey
So to implement this in vb.net i tried following:
Dim nonce = DateTime.Now.ToString()
Dim apiurl = "https://bittrex.com/api/v1.1/account/getbalances?apikey=" + "apikey" + nonce
sign = HashString(apiurl, "apisecret")
Dim request As WebRequest
request = WebRequest.Create(site)
Dim response As WebResponse
request.Method = "GET"
request.Headers.Add("apisign:" + sign)
response = request.GetResponse()
but getting error :(
{"success":false,"message":"NONCE_NOT_PROVIDED","result":null}
Dim nonce = DateTime.Now.Ticks.ToString
Dim apiurl = "https://bittrex.com/api/v1.1/account/getbalances?apikey=" + "ApiKey" + "&nonce=" + nonce
sign = HashString(apiurl, "apisecret")
Dim request As WebRequest
request = WebRequest.Create(site)
Dim response As WebResponse
request.Method = "GET"
request.Headers.Add("apisign:" + sign)
response = request.GetResponse()

How to build valid PUT rest call that requires CSRF token

I get the "400" error when i do this PUT call (vb.net).
What am i doing wrong?
Dim wRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create("https://localhost:8444/api/route/1802/state"), HttpWebRequest)
wRequest.Method = "PUT"
wRequest.ContentType = "text/plain"
Dim stringData As String = "STOP"
Dim data = Encoding.ASCII.GetBytes(stringData)
wRequest.ContentLength = data.Length
Dim newStream = wRequest.GetRequestStream()
newStream.Write(data, 0, data.Length)
newStream.Close()
wResponse = DirectCast(wRequest.GetResponse(), HttpWebResponse)
The last line throw the 400.
this call doc
X-CSRF-Token was missing.
Do a GET and store the CSRF token from the response.
If(String.IsNullOrWhiteSpace(_csrfToken))
_csrfToken = wResponse.Headers("X-CSRF-Token")
End If
Add the token to PUT request before the "GetResponse"
If(not String.IsNullOrWhiteSpace(_csrfToken))
wRequest.Headers("X-CSRF-Token") = _csrfToken
End If
Note: X-CSRF-Token have the lifespan of the session.