I am building a REST Client in C#. I am getting forbidden 403 error. Here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using restservice.webref;
using System.Windows.Forms;
using System.Runtime.Serialization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace restservice
{
class getUUID
{
private const string URL = "http://XXX.XXXX.com/ws410/XXXXX/XX/XX";
public void getProductID()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.Credentials = new NetworkCredential("XXXX", "XX");
request.Accept = #"text/html, application/xhtml+xml, */*";
request.Referer = #"http://www.somesite.com/";
request.Headers.Add("Accept-Language", "en-GB");
request.UserAgent = #"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)";
request.Host = #"www.my.XXX.com";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.ContentType = "application/json";
/*StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Write(false);
requestWriter.Close();*/
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
String htmlString = reader.ReadToEnd();
}
/*
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
Console.Out.WriteLine(response);
responseReader.Close();*/
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
}
}
}
}
I have also given the credentials as well as enabled the default credentials. Still I get the 403 error.
Please can you help?
This might be related to Env. security profile . For example i had the same issue . Added below in spring security yml file securityCollections: - name: "Security" patterns: - "/rootpath/*"
Http Forbidden error usually occurs when you are trying to call the server and server is not allowing the request.
The API that you are calling should whitelist your application IP.
Check if there is any http header restrictions on the API that you are calling.
For Infra related changes you can check this: link
Related
the APi call (Patch) through Visual Studio Console app is failing with the following error
The remote server returned an error: (403) Forbidden.
The same call works fine when I use Postman. I get the response back from Postman(Basic authentication with username and password). What could be the issue with the c# program.
.NET framework 4.7
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml;
using System.Web;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var result = string.Empty;
string json = #"{
""schemas"": [
""urn:scim:schemas:core:2.0:User"",
""urn:scim:schemas:extension:fa:2.0:faUser""
],
""userName"": ""ZMatt.Dandon #cmpy.com"",
""name"": {
""familyName"": ""Dandon"",
""givenName"": ""ZMatt""
},
""displayName"": ""ZMatt Dandon"",
""preferredLanguage"": ""en"",
""active"": false
}";
string url = #"https://url/hcmRestApi/scim/Users/C8FF94E381891376E050480A69294891";
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Making Web Request
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(url);
Req.Credentials = new NetworkCredential("UserName", "Password");
//Content_type
Req.ContentType = "application/vnd.oracle.adf.action+json";
//HTTP method
Req.Method = "PATCH";
using (var streamWriter = new StreamWriter(Req.GetRequestStream()))
{
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)Req.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
}
}
Basic authentication is base64 encoded and added to the HTTP Authorization header.
// Making Web Request
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(url);
//Req.Credentials = new NetworkCredential("00OracleERPuser", "PMT12345");
string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("UTF-8")
.GetBytes("UserName" + ":" + "Password"));
Req.Headers.Add("Authorization", "Basic " + encoded);
I have created a c# library in Visual Studio 2019 on my mac. I am trying to expose a method in my dll which should have the capacity to make an http call and return the response.
But I am getting the error Cannot send a content-body with this verb-type.
I am very new to c#, so I just copy-pasted code from online. Please show me what wrong I am doing.
My Library,
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace ImageTrainer
{
public class Trainer
{
public static void TrainImage()
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create("https://www.abcd.com/rest/city/search/Bang");
request.Method = "GET";
request.ContentType = "application/json";
// // request.ContentLength = DATA.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
// // requestWriter.Write(DATA);
requestWriter.Close();
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
Console.WriteLine(response);
// responseReader.Close();
// Console.WriteLine(response);
}
}
}
and I am using the library in another console application.
using System;
using ImageTrainer;
namespace ImageTrainerTest
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Trainer.TrainImage();
}
}
}
What mistake am I making?
Remove these 2 lines:
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Close();
As you are making GET request, you should not have any body, otherwise you should use POST verb.
I am using C# to call OneSignal Create Notifications API. Its working from my home but when i try to send it from my office, it gives a 400 BAD REQUEST.
The error that i get is
The error that comes is Please include a case-sensitive header of
Authorization: Basic <YOUR-REST-API-KEY-HERE> with a valid REST API key."],
"reference":["https://documentation.onesignal.com/docs/accounts-and-keys#section-keys-ids"]
Also, in office network, when i send it from OneSignal Dashboard it works.
Is it a firewall issue?
Tested with POSTMAN and got the same results. POSTMAN working outside office network and giving 400 Bad Request inside office network.
using System.IO;
using System.Net;
using System.Text;
var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjxx");
var serializer = new JavaScriptSerializer();
var obj = new { app_id = "5eb5a37e-b458-11e3-ac11-000c2940e6xx",
contents = new { en = "English Message" },
include_player_ids = new string[] {"all"} };
var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);
string responseContent = null;
try {
using (var writer = request.GetRequestStream()) {
writer.Write(byteArray, 0, byteArray.Length);
}
using (var response = request.GetResponse() as HttpWebResponse) {
using (var reader = new StreamReader(response.GetResponseStream())) {
responseContent = reader.ReadToEnd();
}
}
}
catch (WebException ex) {
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
System.Diagnostics.Debug.WriteLine(responseContent);
try following
System.Net.CredentialCache credentialCache = new System.Net.CredentialCache();
credentialCache.Add(
new System.Uri("http://www.yoururl.com/"),
"Basic",
new System.Net.NetworkCredential("username", "password")
);
...
...
httpWebRequest.Credentials = credentialCache;
but i think you should use test RESTFUL tools to check what parameters can return correct value at all first.
The issue is solved by adding the onesignal host to our firewall as a trusted site.
I am trying to write some code to connect to an HTTPS site that uses Siteminder authentication.
I keep getting a 401. Any ideas?
I have read a few different things on here but none have really seemed all that helpful. I am also using Fiddler/Firefox Tamper to snoop what's going on.
Here is what I've got so far in regards to code:
try
{
Uri uri = new Uri("https://websiteaddresshere");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri) as HttpWebRequest;
request.Accept = "text/html, application/xhtml+xml, */*";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
// request.Connection = "Keep-Alive";
// request.Method = "Get";
// request.Accept = "text";
request.AllowAutoRedirect = true;
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
Cookie emersoncookie = new Cookie("SMCHALLENGE", "YES");
emersoncookie.Domain = "mydomain";
emersoncookie.Path = "/";
// authentication
var cache = new CredentialCache();
cache.Add(uri, "False", new NetworkCredential("myusername", "mypassword"));
request.Credentials = cache;
// response.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(stream);
MessageBox.Show(stream.ToString());
}
}
}
catch (WebException exception)
{
string responseText;
using (var reader = new StreamReader(exception.Response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
MessageBox.Show(responseText.ToString());
}
}
After doing some more reading on the MSDN website I decided to go a different route.
I ended up making this a service since it will need to be a service at the end of the day and did the following:
CookieContainer emersoncookie = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("https://websiteaddress");
request.Credentials = new NetworkCredential("username", "password");
request.CookieContainer = emersoncookie;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
Stream resStream = response.GetResponseStream();
using (Stream output = File.OpenWrite(#"c:\\somefolder\\somefile.someextention"))
using (Stream input = resStream)
{
input.CopyTo(output);
}
To anyone that might be running into Siteminder authentication issues, this piece of code works pretty well.
I couldn't get Jasen's code to work. Maybe your SM setup is different from mine. But with SiteMinder it's generally a two step authentication process. The code block below works for me:
//Make initial request
RestClient client = new RestClient("http://theResourceDomain/myApp");
client.CookieContainer = new CookieContainer();
IRestResponse response = client.Get(new RestRequest("someProduct/orders"));
//Now add credentials.
client.Authenticator = new HttpBasicAuthenticator("username", "password");
//Get resource from the SiteMinder URI which will redirect to the correct API URI upon authentication.
response = client.Get(new RestRequest(response.ResponseUri));
Although this uses RestSharp, it can be easily replicated using HttpClient or even HttpWebRequest.
I am trying to get the result of the following json webservice https://mtgox.com/code/data/getDepth.php into a string using the following code.
using (WebClient client = new WebClient())
{
string data = client.DownloadString("https://mtgox.com/code/data/getDepth.php");
}
but it always returns a timeout exception and no data. I plan to use fastjson to turn the response into objects and expected that to be that hard part not the returning of the content of the page.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mtgox.com/code/data/getDepth.php");
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string data = sr.ReadToEnd();
}
}
Also resulted in the same error. Can anyone point out what i am doing wrong?
Hmm, strage, this works great for me:
class Program
{
static void Main()
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0";
var result = client.DownloadString("https://mtgox.com/code/data/getDepth.php");
Console.WriteLine(result);
}
}
}
Notice that I am specifying a User Agent HTTP header as it seems that the site is expecting it.
I had similar issue before. request.KeepAlive = false solved my problem. Try this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mtgox.com/code/data/getDepth.php");
request.KeepAlive = false;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string data = sr.ReadToEnd();
}
}