Implement bittrex API in VB.NET - 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()

Related

VB.NET 401 Unauthorized error in PayPal OAuth API

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.

response : unauthorized in Swagger via RestSharp

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

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.

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 401 Unauthorized HTTP Web Request

I'm attempting to login to a cPanel using a POST Request in VB.Net. I have the correct credentials when logging in and when posting I still get an 'Unauthorized (401)' response when it should be '301' (analysed using Tamper Data Firefox Add-On). Below is my post request information and function.
Private Function POSTreq(ByVal URL$, ByVal Data$)
Dim tempCookie As New CookieContainer
Dim DataBytes As Byte() = Encoding.ASCII.GetBytes(Data)
Dim Request As HttpWebRequest = TryCast(WebRequest.Create(URL), HttpWebRequest)
Request.Method = "POST"
Request.ContentType = "application/x-www-form-urlencoded"
Request.ContentLength = DataBytes.Length
Dim PostData As Stream = Request.GetRequestStream()
PostData.Write(DataBytes, 0, DataBytes.Length)
PostData.Close()
Dim Response As HttpWebResponse = Request.GetResponse()
Dim ResponseStream As Stream = Response.GetResponseStream()
Dim StreamReader As New StreamReader(ResponseStream)
Dim Text$ = StreamReader.ReadToEnd()
Return Text
End Function
Post URL
http://example.com:2082/login/
Post Data
login_theme=cpanel&user=USERNAME&pass=PASSWORD&goto_uri=%2F
I could reproduce your described behaviour with your code.
If I set the CookieContainer it works on my side, and I was able to log in:
rem ...
Request.CookieContainer = tempCookie
Request.Method = "POST"
rem ... and so on ...
The second Solution would be to just provide the Credentials:
rem ...
Dim myFullUri = new Uri(URL)
Dim myCredentials As New NetworkCredential(Username, Password)
Dim myCache As New CredentialCache()
rem Add the credentials for that specific host and
rem for "Basic" authentication only
myCache.Add(New Uri(myFullUri.Scheme & "://" & myFullUri.Authority), _
"Basic", myCredentials)
Request.Credentials = myCache
Request.CookieContainer = tempCookie
Request.Method = "POST"
rem ... and so on ...