I am trying to pull JSON from a customer's website, but I get this error.
The code works my local machine.
For other sites, both on my local machine and on the server, the code works.
The site is https://www.vapedepot.ca/wc-api/v1
Does he have a special SSL cert where I need to change my code? Here is my code:
string GetJson(string url)
{
string resultData = string.Empty;
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
myHttpWebRequest.Accept = "application/json";
myHttpWebRequest.Timeout = 6000;
//myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
string userP = m_UserName + ":" + m_Password;
byte[] authBytes = Encoding.UTF8.GetBytes(userP).ToArray();
myHttpWebRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(authBytes));
WebResponse httpResponse = myHttpWebRequest.GetResponse();
Stream responseStream = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
resultData = reader.ReadToEnd();
responseStream.Close();
httpResponse.Close();
return resultData;
}
He is using CloudFlare and the SSL uses ecdsa.
I had the same issue. I swapped to using RestSharp to make my secure web requests and it resolved my issue.
Related
I am using Visual Studio Mac (latest version) and need to fetch data from an IIs server (vaersion 10) with a GET request and by passing a client certificate.
Unfortunately the IIs answers with an RST packet and shows the error:
The I/O operation has been aborted becourse of either a thread exit or an application request.
I know apple uses ATS (I am using iOS 10.3.3).
I guess this has something to do with the client certificate and IIS not accepting it.
Can someone point me to a differnt mono api where I can append the client cert to a GET request?
My code so far is as follows (with request.GetResponse() waiting until timeout...):
X509Certificate2Collection certificates = new X509Certificate2Collection (certificate);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.uriString);
request.ClientCertificates = certificates;
request.Method = "GET";
request.ContentType = "application/json";
request.Accept = "application/json";
request.UserAgent = UserAgentString;
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version11;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse ())
{
this.webResponse = response;
stream = response.GetResponseStream ();
}
I've being working with x509 certificates in order to make secure requests to some data services. They require Two way SSL auth, so I've converted my "Sandbox" certificate (.crt) w/ my Private Key to a Password protected .p12 file.
Here's the first question: Where should I place this .p12 file so that it's readable by my application after deploying to Azure (Using DevOps) but still stored securely? Can I use an my Azure Key Vault?
The second issue is that in my Dev environment I haven't been able to establish the SSL binding after making the request (With a .p12 absolute path):
Here's the code I'm using:
void GetATMs()
{
string requestURL = "https://sandbox.api.visa.com/globalatmlocator/v1/localatms/atmsinquiry";
string userId = "MyUserId";
string password = "MyPassword";
string p12certificatePath = "C:\\Code\\projects\\project\\\\Clients\\PaymentGateways\\Visa\\Certs\\TC_keyAndCertBundle.p12";
string p12certificatePassword = "CertPassword";
string postData = #"{""wsRequestHeaderV2"": { ""requestTs"": ""2018-11-06T03:16:18.000Z"", ""applicationId"": ""VATMLOC"", ""requestMessageId"": ""ICE01-001"", ""userId"": ""CDISIUserID"", ""userBid"": ""10000108"", ""correlationId"": ""909420141104053819418"" }, ""requestData"": { ""culture"": ""en-US"", ""distance"": ""20"", ""distanceUnit"": ""mi"", ""metaDataOptions"": 0, ""location"": { ""address"": null, ""placeName"": ""700 Arch St, Pittsburgh, PA 15212"", ""geocodes"": null }, ""options"": { ""range"": { ""start"": 10, ""count"": 20 }, ""sort"": { ""primary"": ""city"", ""direction"": ""asc"" }, ""operationName"": ""or"", ""findFilters"": [ { ""filterName"": ""OPER_HRS"", ""filterValue"": ""C"" } ], ""useFirstAmbiguous"": true } } }";
HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
request.Method = "POST";
// Add headers
string authString = userId + ":" + password;
var authStringBytes = System.Text.Encoding.UTF8.GetBytes(authString);
string authHeaderString = Convert.ToBase64String(authStringBytes);
request.Headers["Authorization"] = "Basic " + authHeaderString;
// Add certificate
var certificate = new X509Certificate2(p12certificatePath, p12certificatePassword);
request.ClientCertificates.Add(certificate);
request.Accept = "application/json";
var data = Encoding.ASCII.GetBytes(postData);
request.ContentLength = data.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(data, 0, data.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
What am I missing here?
It fails the following way:
An unhandled exception occurred while processing the request.
Win32Exception: The credentials supplied to the package were not recognized
System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface secModule, string package, CredentialUse intent, SCHANNEL_CRED scc)
HttpRequestException: The SSL connection could not be established, see inner exception.
System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
WebException: The SSL connection could not be established, see inner exception. The credentials supplied to the package were not recognized
System.Net.HttpWebRequest.GetResponse()
We have a Wildcard SSL for our domain. Are they different? Can it be registered in the Visa dashboard and used for make secure request as it is signed by a trusted CA authority?
Well, yes. As per, #dagope Recommendation, I've uploaded my certificate to key-management on Azure and access it through the SDK. This is also a best practice for key/certificate management on Azure.
I have the following code sample with which I'm trying to authenticate an Azure active directory user within a Xamarin forms app
The URL (I've removed the actual client ID) works fine in a browser but fails when trying to send the http request
The error message says 'the response type must include client_id'
string URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?"
+ "client_id=xxxx-xxxxx-xxxxx-xxxxx-xxx"
+ "&response_type=code"
+ "&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient"
+ "&response_mode=query"
+ "&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fmail.read"
+ "&state=12345";
var webRequest = System.Net.WebRequest.Create(URL) as HttpWebRequest;
System.Console.WriteLine(URL);
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 20000;
webRequest.ContentType = "text/html";
//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(postData);
}
}
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
Stream resStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
ret = reader.ReadToEnd();
You put parameters in the URL, so you need to use GET method, instead of POST (like your browser does when you paste the URL in its address bar).
So, replace:
webRequest.Method = "POST";
by:
webRequest.Method = "GET";
and remove:
//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(postData);
}
I am using this code to get the deployment configurations.
X509Store certificateStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
certificateStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = certificateStore.Certificates.Find(
X509FindType.FindByThumbprint, certThumb, false);
if (certs.Count == 0)
{
Console.WriteLine("Couldn't find the certificate with thumbprint:" + certThumb);
return;
}
certificateStore.Close();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
new Uri("https://management.core.windows.net/" + subID +
"/services/hostedservices/" + hostedServiceName +
"/deploymentslots/" + deploymentType));
request.Method = "GET";
request.ClientCertificates.Add(certs[0]);
request.ContentType = "application/xml";
request.Headers.Add("x-ms-version", "2009-10-01");
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Parse the web response.
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
// Display the raw response.
Console.WriteLine("Deployment Details:");
string deployment = reader.ReadToEnd();
// Close the resources no longer needed.
responseStream.Close();
}
But I am getting configuration in encrypted format.
But if run azure powershell it gives me the configuration in plain text.
$deployment = Get-AzureDeployment -ServiceName $serviceName -Slot $slot
$deployedConfig = $deployment.Configuration
Since I have to use service management API how can I do it?
This is the expected behavior. REST API returns the data in Base64 encoded format. Since Windows Azure PowerShell consumes the same REST API, they convert the data from Base64 format and present it in humanly readable format. This is what you would also need to do.
So in your code you would do something like this:
string clearText = System.Text.Encoding.UTF8.GetString(
Convert.FromBase64String(reader.ReadToEnd()));
I have some problem in my project. I want to delete my file from the ftp using proxy.
My code is:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + FtpServerName + FtpFilePath);
request.Method = WebRequestMethods.Ftp.DeleteFile;
request.Proxy = new WebProxy(ProxyAddress);
request.Proxy.Credentials = new NetworkCredential(ProxyUserName, ProxyPassword);
request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
In this i'm getting error like:
The requested FTP Command is not supported when using http proxy
can any one please help me
Thanks in advance
from http://blogs.msdn.com/b/adarshk/archive/2004/09/13/229069.aspx:
Note on using Http Proxy on FTPWebRequest: Http proxy is only supported for limited number of ftp methods (mainly to download file only), so if you have IE settings for proxy on your machine you need to explicitly set FtpWebRequest to not use proxy like below
request.Proxy = GlobalProxySelection.GetEmptyWebProxy();
If you want to perform other FTP actions through a proxy, you'll have to find another FTP component that supports it.
Instead of request.Proxy = GlobalProxySelection.GetEmptyWebProxy();
try request.Proxy = WebRequest.DefaultWebProxy;
Follows a demo code that worked well for me:
var request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://99.999.99.99/TextFile1.txt"));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("ftp_user", "ftp_pass"); // it's FTP credentials, not proxy
request.Proxy = WebRequest.DefaultWebProxy;
var sourceStream = new StreamReader("TextFile1.txt");
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
var response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();