RestSharp response forbidden - api

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

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)

How to obtain Access Token using production environment in DocuSign?

In Docusing I am obtained access token with demo account successfully and create envelope also, when I move to production account, I can't get access token and got error as "The remote server returned an error: (400) Bad Request." I did 20 API calls successfully and reviewed and make Go to live from developer account, API key details reflects on production login also.
Old Code
This is the code I used to obtain access token.
Dim PrivateKey As String = odjDTRep.Rows(0)("PrivateKey").ToString().Trim.Replace(vbLf, "").Replace(vbCr, "")
'This section to generate jwt Header
Dim ar1 As JObject = New JObject()
ar1.Add("typ", "JWT")
ar1.Add("alg", "RS256")
Dim header As String = Base64UrlEncoder.Encode(ar1.ToString)
'This section to generate jwt Body
Dim ar2 As JObject = New JObject()
ar2.Add("iss", odjDTRep.Rows(0)("iss_Int_Key").ToString())
ar2.Add("sub", odjDTRep.Rows(0)("sub1_Api_UserName").ToString())
ar2.Add("iat", DateDiff(DateInterval.Second, New Date(1970, 1, 1), Now().ToUniversalTime))
ar2.Add("exp", DateDiff(DateInterval.Second, New Date(1970, 1, 1), DateAdd(DateInterval.Hour, 1, Now().ToUniversalTime)))
ar2.Add("aud", odjDTRep.Rows(0)("aud").ToString())' aud i pass account.docusign.com
ar2.Add("scope", odjDTRep.Rows(0)("scope").ToString())
Dim body As String = Base64UrlEncoder.Encode(ar2.ToString)
Dim stringToSign As String = header & "." & body
Dim bytesToSign() As Byte = Encoding.UTF8.GetBytes(stringToSign)
Dim keyBytes() As Byte = Convert.FromBase64String(PrivateKey)
Dim privKeyObj = Asn1Object.FromByteArray(keyBytes)
Dim privStruct = RsaPrivateKeyStructure.GetInstance(privKeyObj)
'This section to generate jwt Signature
Dim sig As ISigner = SignerUtilities.GetSigner("SHA256withRSA")
sig.Init(True, New RsaKeyParameters(True, privStruct.Modulus, privStruct.PrivateExponent))
sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length)
Dim signature() As Byte = sig.GenerateSignature()
Dim sign As String = Base64UrlEncoder.Encode(signature)
Dim a As String = header & "." & body & "." & sign
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
ServicePointManager.SecurityProtocol = DirectCast(3072, SecurityProtocolType)
ServicePointManager.Expect100Continue = True
Dim request As WebRequest = WebRequest.Create("https://account.docusign.com/oauth/token?grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=" & a & "")
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = 0
request.Headers.Add("X-DocuSign-Authentication", "{ ""Username"":""" & odjDTRep.Rows(0)("UserName").ToString() & """, ""Password"":""" & odjDTRep.Rows(0)("Password").ToString() & """, ""IntegratorKey"":""" & odjDTRep.Rows(0)("iss_Int_Key").ToString() & """ }")
Dim response As WebResponse = request.GetResponse()
Console.WriteLine((CType(response, HttpWebResponse)).StatusCode)
If (CType(response, HttpWebResponse)).StatusCode <> HttpStatusCode.OK Then
Return "002:Fail"
End If
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
All details I read from SQL table and store in DataTable, from DataTable I pass all details in that code. Any other URL I need change above I mention for production environment?
New code to obtain Access token
var apiCent = new ApiClient("https://demo.docusign.net/restapi");
string ik = "xxxx-6a8b-4a7d-ba0f-xxxx";
string userId = "xxxxx-db97-xxx-a398-0e5986fadf49";
string accountId = "xxxxx-3e10-42af-xxxxx-xxxx";
string envId = "";
string authserver = "account.docusign.com";
string rsaKey = "xxxxxxxxxi7+b8i7SmfRdx8sExxxxxxxKmwIbLFOv1LtmUk/KRP8wPmMeNpq10kAzizzAeqnuBgW9ECHjV/gUA984dzk128UPmIRqTW+69e1dSknGA+nJWshyZEqJXmvFB8Ueie5EiCW6FIlXpdLVWwmJwUGiQQsV+r8hpmbhSImr5A40HQPPpasYAnKPNDgRbKwxrOONrCdUUre34Up2sk8gcAcMQRwKosPBn6/dAXadYP0sKEGSVKogguNSCyoHOLh74MPepDLnEVs9VAiyk+zQEmZxYaXhrV4pvO2C5WNXdnqHUdcC/McZOBVGwRdG0xOaC8t4lplJHjiis+8YQEWQIDAQABAoIBACTzxYJBBWGtVXRyqo+jzqmSOKJrBumvtHlC6k7IvYYInJI3IVPV44pC+eROAdDiYgQE9LZvag2MW7A8IAeYwWJZhBKCq8odz4plgJaZwX2YdItDP4kSjIOco5W4lMjMQd66KNMTKFkS2fgbtBF0crogO8cuAwn+kZtsdFH8IKA+LPQjvp09yXZvDN6Q8XTKfcIkW2TqthdUOcJP65h72KwQnQGGvTDAd8p3OsHqAt7LEwW6xg0ci2HT1fGZbdwrXVHFHX9mFPndLmQ1CZlwX8XiVIHYPdbEEjO+3U29jGsi/k8+h54ngcf5H1An8t+fdDVzknprbCGOIdynnLFq0CgYEA1os/qHEXObHe+Yn2EQWM924hPtOjY5Z6p60EEALaaKVLYiCyhI7fXkhfB0475gC0+HhGgyu0zts04iOE2Agr8Yc8jAkZ3/UGOrbBFoSSyHvKYQaYqdWJ4HjbV3L5jkWSzplmn5/KFM9COMecEpx0cXkhxt1MMC5gu3WKU5QWhMcCgYEAvdLlwOf33KUsG/dojZAtzK6Lz6UoBi+nHHg9jZ2V561xSzhrGGBTRkpUL5kf66AOrHRNYZvNX051WCzsQ94NBOzgwykhqcC+gYBx6ravoBgyyrw/YICQB69xkxJlq/uGZQf3cvcPfcxFbjySzjCqgmgXewmqJE2U0drnhDVzd8CgYBOGViuB6UNwptJuZgSsDOVqsh9Z2t2CERUH553+aHqMCnV6dMygBP97Vhyf188pgs63AXHIDTsjE2e+JEWVzsv7Cv1SibaKQcAfqChgtcwFigg09blFC/hv/0Qw3DnApqjjKIX/4H/u0b/BmLhP4T//bl2+/4NGATsmKgnLqRX5wKBgBFP36ZVQZS896XhTYbDpHmrXZLldB4EUJBXIv38ZkSH2/JJRfMmLdIWS1E//NpHca8muDvzsqpDhJn7qMe4KnVNaqzEBWlGaA4XaCgmm+aN3MYKt4nXRo9EfnhMUtXMW8G3caSPyBlapv5dLLPRjGdnk1mdhPUQsUytEdKLpIQvAoGAbcb1rHbHv9AlmBBq5JODGgfN9GbLpPR6KyCtUGPhIrcSyZF00PcIEckwwt1XvqFJXFzFWCs9SEq7YbmGKuxSVZ7NLOOLaX6lZ3HdBiHvqcsCdMiqw9egTqqkn2po7pGCQzwxYmGLBfF+MXDo3KTynvNMz31efrZlmQsVq3VBt9U=";
var scopes = new List<string>
{
"signature"
};
OAuth.OAuthToken authToken = apiCent.RequestJWTUserToken(ik, userId, authserver,Encoding.UTF8.GetBytes(rsaKey), 1, scopes);
string accessToken = authToken.access_token;
Now i am getting error as "Unexpected PEM type" , in production account i take IK,UserID and generated new RSA key.
First off, using legacy auth is not allowed for new applications. You are using the X-DocuSign-Authentication header with clear text password which is a legacy mechanism to authenticate. It is insecure and cannot be used.
When using JWT authentication and changing from the developer environment to the production environment you have to do the following:
Pass go-live and get approval to have your IK (app) in production.
Promote your IK to your production account.
Create a new RSA key for the new IK in the production account. You cannot use the RSA key from your developer account.
The URL for authentication is changed from https://account-s.docusign.com to https://account.docusign.com
userId for the user will be different GUID - need to update
accountId for the account will be different GUID - need to update

error 'The given key was not present in the dictionary' when trying to API HTTP request token with Blue Prism

Im trying to use the Blue Prism object HTTP request to get an access token for further processing the items. However, i couldn't manage to get the token due to the error 'The given key was not present in the dictionary'. I have looked all parameters and still didn't manage to solve the issue. I use a built in visual basic code to get the result as a collection which is later parsed to JSON to get the token.
The underlying visual basic code is:
Dim request As WebRequest = WebRequest.Create(addressURL)
If forcePreAuth Then
'Sometimes a web server will require the authorisation header in the initial request
'In which case we have to add the basic authorization header manually.
Dim bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}",username,password))
Dim base64 As String = Convert.ToBase64String(bytes)
request.Headers.Add("Authorization", "Basic " & base64)
Else
If Not String.IsNullOrEmpty(username) AndAlso Not String.IsNullOrEmpty(password) Then
request.Credentials = New NetworkCredential(username,password)
End If
End If
If useProxy Then
Dim proxyURI As New Uri(proxyURL)
Dim proxy As New WebProxy(proxyURI, True)
Dim proxyCred As New NetworkCredential(proxyUsername, proxyPassword)
Dim credCache As New CredentialCache()
credCache.Add(proxyURI, "Basic", proxyCred)
proxy.UseDefaultCredentials = False
proxy.Credentials = credCache
request.Proxy = proxy
End If
request.Method = method
request.ContentType = contentType
Dim httpRequest As HttpWebRequest = TryCast(request, HttpWebRequest)
If httpRequest IsNot Nothing Then
If Not String.IsNullOrEmpty(accept) Then
httpRequest.Accept = accept
End If
If Not String.IsNullOrEmpty(certID) Then
httpRequest.ClientCertificates.Add(m_Certificates(certID))
End If
End If
For Each r As DataRow In headers.Rows
For Each c As DataColumn In headers.Columns
Dim columnName As String = c.ColumnName
Dim val As String = r(columnName).ToString
request.Headers.Add(columnName,val)
Next
Exit For 'Only one row is allowed
Next
If Not String.IsNullOrEmpty(body) Then
Dim requestStream As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(requestStream, New Text.UTF8Encoding(False))
sw.Write(body)
End Using
End If
Using response As WebResponse = request.GetResponse()
Dim responseStream As IO.Stream = response.GetResponseStream()
Dim sr As New IO.StreamReader(responseStream)
resultData = sr.ReadToEnd()
End Using
Screenshots:
Input parameter
Input parameter request token
Request token:
Output parameter:
Blue Prism uses a bit of a peculiar pattern regarding Certificates. The way the Utility - HTTP object is designed is to allow for the loading of certificate files (.cer, etc) on-the-fly into a local Certificate Store, which assigns a new Certificate ID each time.
Before firing your HTTP Request, use the Load Certificate action within the same Utility - HTTP object to output a valid Certificate ID, which you can then pass to HTTP Request's Certificate ID parameter.

PayPal POST payment not working on mobile browsers

I have a web application written in VB.net. I implemented the payment via paypal.
When I make a payment via pc there is no problem, but when I make a payment via mobile I have some problems.
I can't read the paypal parameters on my return page.
I used httpwebrequest for read the info from paypal, but the variables request.form is empty, so the response is "INVALID".
is there anyone who can help me??? please...
This is my code:
Dim objHttp As HttpWebRequest
objHttp = WebRequest.Create("https://www.sandbox.paypal.com/cgi-bin/webscr")
objHttp.Method = "POST"
objHttp.ContentType = "application/x-www-form-urlencoded"
Dim param As Byte() = Request.BinaryRead(HttpContext.Current.Request.ContentLength)
Dim strRequest As String = Encoding.ASCII.GetString(param)
Dim ipnPost As String = strRequest
strRequest += "&cmd=_notify-validate"
objHttp.ContentLength = strRequest.Length
'Send the request to PayPal and get the response
Dim streamOut As New StreamWriter(objHttp.GetRequestStream(), System.Text.Encoding.ASCII)
streamOut.Write(strRequest)
streamOut.Close()
Dim streamIn As New StreamReader(objHttp.GetResponse().GetResponseStream())
Dim strResponse As String = streamIn.ReadToEnd()
streamIn.Close()
Dim myHttpWebResponse As HttpWebResponse = CType(objHttp.GetResponse(), HttpWebResponse)
Dim strIdTransazione = Request.Form("txn_id")
Dim strDscTransazione = Request.Form("payment_status")
'HttpStatusCode.myHttpWebResponse.StatusCode()
If myHttpWebResponse.StatusCode <> HttpStatusCode.OK Then
Else
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.