I have a script dat i want to convert to modern authentication. I cant find the right properties to do it. Could you help me?
HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
HttpWebRequest.DefaultCachePolicy = policy;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = noCachePolicy;
request.Method = "GET";
string encoded = "username:password";
request.Headers.Add("Authorization", "Basic " + encoded);
request.ContentType = "application/xml";
request.Headers["x-api-key"] = "12312312-1234-1234-1234-123123123123";
ServicePointManager.ServerCertificateValidationCallback = delegate (
Object obj, X509Certificate certificate, X509Chain chain,
SslPolicyErrors errors)
{
return (true);
};
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
Console.WriteLine(responseStr);
return responseStr;
}
}
catch (Exception e)
{
Task.Run(() =>
{
});
}
I probaly need something like ConfidentialClientApplicationBuilder but i cant seem to find how to do it.
Related
I'm trying to use the check_eligibility call from the eBay Post-Order API in C# very unsuccessfully. Every time I get a bad response. Here is one way I've tried:
string url = "https://api.ebay.com/post-order/v2/cancellation/check_eligibility";
HttpWebRequest cancelOrderRequest = (HttpWebRequest)WebRequest.Create(url);
cancelOrderRequest.Headers.Add("Authorization", "TOKEN " + AuthToken);
cancelOrderRequest.ContentType = "application/json";
cancelOrderRequest.Accept = "application/json";
cancelOrderRequest.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY_US");
cancelOrderRequest.Headers.Add("legacyOrderId", ebayFullOrderId);
cancelOrderRequest.Method = "POST";
HttpWebResponse response = (HttpWebResponse)cancelOrderRequest.GetResponse();
And here is another way I've tried:
string url = "https://api.ebay.com/post-order/v2/cancellation/check_eligibility";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", "TOKEN " + AuthToken);
httpWebRequest.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY_US");
httpWebRequest.Accept = "application/json";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"legacyOrderId\":\"###-###\"";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Regardless of which way I try both came back with the same message, "The remote server returned an error: (400) Bad Request." If anyone could point me in the right direction I'd greatly appreciate it. Thanks.
My second code example ended up being the correct way to solve my problem. What I realized was my json was slightly off. I was missing the extra } at the end. The below updated json syntax fixed my problem going with the code from my second example.
var json = "{\"legacyOrderId\":\"" + ebayFullOrderId + "\"}";
Please try this code:
private void MakeRequests()
{
HttpWebResponse response;
if (RequestEbay(out response))
{
response.Close();
}
}
private bool RequestEbay(out HttpWebResponse response)
{
response = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.ebay.com/ws/api.dll");
request.Headers.Add("X-EBAY-API-SITEID", #"0");
request.Headers.Add("X-EBAY-API-COMPATIBILITY-LEVEL", #"967");
request.Headers.Add("X-EBAY-API-CALL-NAME", #"GetOrders");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string body = #"<?xml version=""1.0"" encoding=""utf-8""?>
<GetOrdersRequest xmlns=""urn:ebay:apis:eBLBaseComponents"">
<RequesterCredentials>
<eBayAuthToken>!!!!!!!!!!!!!!!!YOUR EBAY TOKEN!!!!!!!!!!!!!!!!1</eBayAuthToken>
</RequesterCredentials>
<ErrorLanguage>en_US</ErrorLanguage>
<WarningLevel>High</WarningLevel>
<CreateTimeFrom>2016-12-01T19:09:02.768Z</CreateTimeFrom>
<CreateTimeTo>2017-12-15T19:09:02.768Z</CreateTimeTo>
<OrderRole>Seller</OrderRole>
</GetOrdersRequest>";
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response;
else return false;
}
catch (Exception)
{
if(response != null) response.Close();
return false;
}
return true;
}
I looked up every single page on google there was no clear answer
right now this is my code:
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.hesabit.com/oauth2/token");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
string result_st;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"code\":\"{atho code}\"," +
"\"grant_type\":\"authorization_code\"," +
"\"client_id\":\"{client_id}\"," +
"\"client_secret\":\"{client_secret}\"," +
"\"redirect_uri\":\"{redirect_uri}\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
result_st = result;
}
return result_st;
}
catch (Exception ex)
{
return ex.ToString();
}
Your code looks very RAW, you should use some helpful libraries like Newtonsoft.JSON and RestSharp
In NET 4.0 you can use
public TResponse Send<TRequest, TResponse>(string url, TRequest request)
{
var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.ContentType = "application/json";
ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
var json = Newtonsoft.Json.JsonConvert.SerializeObject(request);
using (var requestStream = webRequest.GetRequestStream())
{
using (var writer = new StreamWriter(requestStream))
{
writer.Write(json);
}
}
try
{
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (var responseStream = webResponse.GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
var responseData = reader.ReadToEnd();
webResponse.Close();
return Newtonsoft.Json.JsonConvert.DeserializeObject<TResponse>(responseData);
}
}
}
}
catch (WebException ex)
{
throw ProcessWebException(ex); // ToDo
}
}
In NET 4.5 you can use
public async Task<TResponse> ExecuteAsync<TRequest, TResponse>(string url, TRequest request)
{
ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
using (var handler = new HttpClientHandler() {})
{
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var json = Newtonsoft.Json.JsonConvert.SerializeObject(request);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var processResult = await client.PostAsync(url, httpContent);
var responseBody = processResult.Content.ReadAsStringAsync().Result;
return Newtonsoft.Json.JsonConvert.DeserializeObject<TResponse>(responseBody);
}
}
}
In example i use Newtonsoft.Json library.
im making an app in wpf, which uses a restful api, from sharefile im making the autorisation
so far i have this
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("https://secure.sharefile.com/oauth/authorize");
HttpWebRequest request = WebRequest.CreateHttp(uri);
shareFileWebView.Navigate(uri);
request.Method = "POST";
shareFileWebView. // but i supose to get something from here
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(response.StatusCode);
JObject token = null;
using (var reader = new StreamReader(response.GetResponseStream()))
{
string body = reader.ReadToEnd();
token = JObject.Parse(body);
}
OAuth2Token _tokene =new OAuth2Token(token);
}
i need to get that token but how can i get from the webbrowser? in the webr browser the user fills his accounts data, any ideas??
Does this link give you what you need?
http://api.sharefile.com/rest/api-key.aspx
Http request with body ( for example send image ) :
public string httpRequest(string url,byte[] image)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "Post";
request.ContentType = "multipart/form-data";
request.ContentLength = image.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(image, 0, image.Length);
postStream.Close();
WebResponse response = request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
if (!string.IsNullOrEmpty(responseString))
return responseString;
return null;
}
}
catch (Exception ex)
{
return ex.Message;
}
}
or :
public string RunCommand()
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
var request = (HttpWebRequest)WebRequest.Create("url");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
response.Close();
return responseString;
}
I am trying to access a SSL page via HttpWebRequest. It looks like the page uses JavaScript. I can get the login page, but after I login (I think its logged in), I cannot get the next page. Here is my code:
private void fetch(String password)
{
try
{
ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
CookieContainer cookies = new CookieContainer();
HttpWebRequest http = (HttpWebRequest)WebRequest.Create("https://facebook.com/");
http.CookieContainer = cookies;
http.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)";
IWebProxy proxy = http.Proxy;
if (proxy != null)
{
Console.WriteLine("Proxy: {0}", proxy.GetProxy(http.RequestUri));
}
else
{
Console.WriteLine("Proxy is null; no proxy will be used");
}
WebProxy myProxy = new WebProxy();
Uri newUri = new Uri("myproxy");
myProxy.Address = newUri;
myProxy.Credentials = new NetworkCredential("username", password);
http.Proxy = myProxy;
HttpWebResponse response = (HttpWebResponse)http.GetResponse();
/////////////////////////////////////////////////////////
HttpStatusCode responseStatus;
responseStatus = response.StatusCode;
if (responseStatus == HttpStatusCode.OK)
{
UriBuilder urlBuilder = new UriBuilder("https://facebook.com/");
ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlBuilder.ToString());
request.CookieContainer = cookies;
request.Referer = formUrl.ToString();
request.Method = "POST";
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)";
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(requestStream, Encoding.ASCII))
{
request.PreAuthenticate = true;
ICredentials credentials = new NetworkCredential("username", password);
request.Credentials = credentials;
request.Method = "POST";
}
string responseContent = null;
using (HttpWebResponse response2 = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response2.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
responseContent = responseReader.ReadToEnd();
}
Console.WriteLine(responseContent);
response.Close();
response2.Close();
}
}
}
else
{
Console.WriteLine("Client was unable to connect!");
}
}
catch (UriFormatException e)
{
Console.WriteLine("Invalid URL");
}
catch (IOException e)
{
Console.WriteLine("Could not connect to URL");
}
}
I'm trying to connect to a web service using C# and digest authentication, but every time I got the 401 - Not Authorized error. But when I try to reach the service over Firefox, everything's OK. When I use IE8, my password is not accepted and I got a 401.
Do you have any ideas? Thanks for the help.
Here's the test code I'm using:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback
= delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
Uri uri = new Uri(URL);
NetworkCredential netCredential = new NetworkCredential(username, password);
CredentialCache cache = new CredentialCache();
cache.Add(URL, 443, "Digest", netCredential);
WebRequest request = WebRequest.Create(URL);
request.Credentials = cache;
request.PreAuthenticate = true;
request.Method = "POST";
WebResponse response;
try
{
response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
Response.Write(result);
response.Close();
reader.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message + "<br/><br/><br/>");
Response.Write("Request Headers<br/><br/>");
WebHeaderCollection headers = request.Headers;
// Get each header and display each value.
foreach (string key in headers.AllKeys)
{
string value = headers[key];
Response.Write(key + ": " + value);
Response.Write("<br/><br/>");
}
}
You are using the wrong overload of CredentialCache.Add, you should use CredentialCache.Add(Uri, string, NetworkCredential) instead. The first one (with the port number) is only for SMTP.
cache.Add(uri, "Digest", netCredential);