Error: (403) Forbidden - c#

I'm trying to do a HttpWebRequest(POST) to send some data to a server. However I always got error: (403) Forbidden. This is my current code:
foreach (Patient patient in patients)
{
string[] names = patient.Nome.Split(' ');
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8090/ehr/rest/createPerson");
request.Headers.Add("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXh0cmFkYXRhIjp7Im9yZ2FuaXphdGlvbiI6IjY2NjYifSwiaXNzdWVkX2F0IjoiMjAxNi0wNC0yMlQxMzo0ODoyOS40ODRaIn0=.Fztrd8LR/FkBY2CJLjnl/qYYYjz1/vr4g01e8yTad/0=");
request.Accept = "application/json";
string tempUrl = "firstName=" + names[0];
tempUrl += "&lastName=" + names[names.Length - 1];
tempUrl += "&dob=" + patient.Data_Nasc;
tempUrl += "&role=pat";
tempUrl += "&sex=" + "M";
tempUrl += "&organizationUid=" + organization.Uid;
var data = Encoding.ASCII.GetBytes(tempUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
stream.Close();
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
I know that there is a lot of questions about this error, but no answer resolve my problem. Im still getting error 403.
Next is the stacktrace:
at System.Net.HttpWebRequest.GetResponse()
at IndexDocClinicos.Classes.EhrData.createPersons() in c:\Users\Joaogcorreia\Desktop\EHR + Solr + IndexDocClinicos\Indexacao-de-Documentos-Clinicos\Indexação de Documentos Clinicos\IndexDocClinicos\Classes\EhrData.cs:line 163
at IndexDocClinicos.WebApiApplication.Application_Start() in c:\Users\Joaogcorreia\Desktop\EHR + Solr + IndexDocClinicos\Indexacao-de-Documentos-Clinicos\Indexação de Documentos Clinicos\IndexDocClinicos\Global.asax.cs:line 37
I already tried this POST with Insomnia and it works very well. So I have no ideia what is wrong. I also verified and the token is correct.
pls help
thanks =)

Related

oauth 2.0 in c# getting 400 error unsure why

i am trying to fetch an access token by calling an API with an auth code and keeping getting a 400 error.
I have read many a web sites and can't see what is wrong with this. thanks. I have left in commented bits as this is other ways I have tried. Appreciate any quick advice
HttpWebRequest request = WebRequest.Create("https://identity.xero.com/connect/token") as HttpWebRequest;
request.Headers.Add("Authorization", "Basic " + b64_id_secret);
//string data = "{ grant_type : refresh_token, refresh_token : " + l_auth_code+ "}";
//string data = "{ 'grant_type' : 'authorization_code', 'code' : '" + l_auth_code + "', 'redirect_uri' : '" + C_XERO_REDIRECT_URL + "'}";
request.ContentType = "application/json";
request.Method = "POST";
//request.ContentType = "application/json";
//request.ContentLength = postBytes.Length;
//request.Accept = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"grant_type\":\"authorization_code\"," +
"\"code\":\"" + l_auth_code + "\","+
"\"redirect_uri\":\"" + C_XERO_REDIRECT_URL + "\"}";
streamWriter.Write(json);
}
// crashes here
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}

Getting System.IO.IOException in mscorlib.dll

i try to make an HTTP POST to an Swagger UI api and wrote this rudimentary Code:
string baseip = "192.168.0.1";
string auth = "authcodre";
string name = "TestMan";
string ip = "1.1.1.1";
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
string URL = "https://" + baseip + ":4444/api/objects/network/host/";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.ContentType = "application/json";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("token:" + auth));
request.PreAuthenticate = true;
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string patchtxt = "{ \"name\": \"" + name + "\", \"_type\": \"network/host\", \"address\": \"" + ip + "\"}";
streamWriter.Write(patchtxt);
streamWriter.Flush();
streamWriter.Close();
Console.WriteLine("Patches");
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); //Einlesen der HTTP-Antwort
string resppatch = reader.ReadToEnd();
Console.WriteLine(resppatch);
Console.ReadLine();
}
It throws me an System.IO.IOException" in mscorlib.dll at this line:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
Can anyone explain why this happens and how to fix it?
Thank you :)

$_POST global empty when uploading a file using HttpWebRequest in C#

I have a c# function that is used to upload a file to a PHP web service. The PHP web service is expecting the following
A POST parameter called UploadFileRequestDto containing some XML data
The File stream
For some odd reason the $_POST parameter contains the UploadFileRequestDto only some of the time. If I look at the contents of
file_get_contents("php://input"))
I can see that the request is comming through as expected with the UploadFileRequestDto included.
Doing a
print_r($_REQUEST)
is returning an empty array.
Can anyone help me with a solution to this problem, my C# function is stipulated below
public string UploadFile(UploadFileRequestDto uploadFileRequestDto,string fileToUpload, string fileUploadEndpoint)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(fileUploadEndpoint);
request.ReadWriteTimeout = 1000 * 60 * 10;
request.Timeout = 1000 * 60 * 10;
request.KeepAlive = false;
var boundary = "B0unD-Ary";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
var postData = "--" + boundary + "\r\nContent-Disposition: form-data;";
postData += "name=\"UploadFileRequestDto\"\r\n\r\n";
postData += string.Format("{0}\r\n", SerializeUploadfileRequestDto(uploadFileRequestDto));
postData += "--" + boundary + "\r\n";
postData += "--" + boundary + "\r\nContent-Disposition: form-data;name=\"file\";filename=\"" + Path.GetFileName(fileToUpload) + "\"\r\n";
postData += "Content-Type: multipart/form-data\r\n\r\n";
var byteArray = Encoding.UTF8.GetBytes(postData);
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] filedata = null;
using (var reader = new BinaryReader(File.OpenRead(fileToUpload)))
{
filedata = reader.ReadBytes((int)reader.BaseStream.Length);
}
request.ContentLength = byteArray.Length + filedata.Length + boundaryBytes.Length;
request.GetRequestStream().Write(byteArray, 0, byteArray.Length);
request.GetRequestStream().Write(filedata, 0, filedata.Length);
request.GetRequestStream().Write(boundaryBytes, 0, boundaryBytes.Length);
var response = request.GetResponse();
var data = response.GetResponseStream();
var sReader = new StreamReader(data);
var sResponse = sReader.ReadToEnd();
response.Close();
return sResponse.TrimStart(new char[] { '\r', '\n' });
}
catch (Exception ex)
{
LogProvider.Error(string.Format("OzLib.Infrastructure : WebHelper : public string UploadFile(UploadFileRequestDto uploadFileRequestDto, string fileUploadEndpoint) : Exception = {0}", ex.ToString()));
}
Ok I found the problem, the
post_max_size
setting in the php.ini was set to 8M and some of the files I was trying to upload exeeded 8M. Changed this setting to 16M and restarted the PHP service.
When the file size exeeds the limit that was set the $_POST global is empty.

Can't update a custom object in Appcelerator Cloud Service, got an error: (401) Unauthorized

I'm working on a C# application that connects to the Appcelerator Cloud Service, so far I can make queries and login, but when I tried to update a Custom Object I got the following error: The remote server returned an error: (401) Unauthorized. This is my code for my POST request:
url = "https://api.cloud.appcelerator.com/v1/objects/Reservacion/update.json?key=appkey&id=" + idReservacion + "&noDisponibles=" + noDisponibles;
wrGetUrl = (HttpWebRequest)WebRequest.Create(url);
wrGetUrl.Method = "POST";
wrGetUrl.ContentType = "application/json";
objStream = wrGetUrl.GetResponse().GetResponseStream(); // this is the line where the error is thrown
reader = new StreamReader(objStream);
I have a theory and it involves the login, at the beginning of my application I make a login which return an ok status, but I think I need to somehow let know ACS I logged in already by sending the session id or something like that when I try to update the Custom Object.
Edit That is why I tried to add the cookie in the header like this:
url = "https://api.cloud.appcelerator.com/v1/objects/Reservacion/update.json?key=appkey&id=" + idReservacion + "&noDisponibles=" + noDisponibles;
wrGetUrl = (HttpWebRequest)WebRequest.Create(url);
wrGetUrl.Method = "POST";
wrGetUrl.ContentType = "application/json";
wrGetUrl.Headers.Add("Set-Cookie", "_session_id=" + session + "; path=/; HttpOnly");
objStream = wrGetUrl.GetResponse().GetResponseStream(); // this is the line where the error is thrown
reader = new StreamReader(objStream);
Where session is the session id I got from my successful login. But even though I added this to the headers in my request the error The remote server returned an error: (401) Unauthorized.
Edit:
I tried something else:
url = "https://api.cloud.appcelerator.com/v1/objects/Reservacion/update.json?key=appkey&id=" + idReservacion + "&noDisponibles=" + noDisponibles;
wrGetUrl = (HttpWebRequest)WebRequest.Create(url);
wrGetUrl.Method = "POST";
wrGetUrl.ContentType = "application/json";
wrGetUrl.Headers.Add("Cookie", session); //changed the header but it didn't work
objStream = wrGetUrl.GetResponse().GetResponseStream(); // still throws the same error
reader = new StreamReader(objStream);
How can I solve this problem? Thanks for any help in advance.
I solved the problem like this:
String fields = "fields={\"noDisponibles\":" + noDisponibles +"}";
String url = "https://api.cloud.appcelerator.com/v1/objects/Reservacion/update.json?key=appkey&id=" + idReservacion + "&_session_id="+session;
HttpWebRequest wrGetUrl = (HttpWebRequest)WebRequest.Create(url);
wrGetUrl.Method = "PUT";
wrGetUrl.ContentLength = fields.Length;
wrGetUrl.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = wrGetUrl.GetRequestStream();
byte[] byteArray = Encoding.ASCII.GetBytes(fields);
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
Stream objStream = wrGetUrl.GetResponse().GetResponseStream();
StreamReader reader = new StreamReader(objStream);
I had to write in the DataStream of my HttpWebRequest to send the fields I wanted to update. Hope this may help people in the future.

WebResponse dynamically 'sometimes' crash

I have a foreach with an "If" and when the condition is true, I do a WebResponse to post my item in a server.
Sometimes the code run for two o more items but other times crashes with the following error:
The remote server returned an error: (407) Proxy Authentication Required.
The code:
WebClient client = new WebClient();
string authInfo = "admin:geoserver";
string address = "http://xxxxxxxx:8080/geoserver/rest/workspaces/";
client.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
WebRequest request = WebRequest.Create(address);
request.ContentType = "text/xml";
request.Method = "POST";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
byte[] bret = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>" + nameWS + "</name></workspace>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(bret, 0, bret.Length);
reqstr.Close();
try
{
WebResponse response = request.GetResponse();
response.Close();
}
My Environment is C# Visual Studio 2010
how often do you call this? as others have suggested it could be that the server is protected from DOS and your requests are seen like that. It's also valuable to dispose immediately all disposable objects with a using block for example. we had some issues once while leaving too many connections open to our web server, internally in our network. You could adjust your code to look like this:
using(var client = new WebClient())
{
string authInfo = "admin:geoserver";
string address = "http://xxxxxxxx:8080/geoserver/rest/workspaces/";
client.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
var request = WebRequest.Create(address);
request.ContentType = "text/xml";
request.Method = "POST";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
byte[] bret = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>" + nameWS + "</name></workspace>");
using (var reqstr = request.GetRequestStream())
{
reqstr.Write(bret, 0, bret.Length);
}
try
{
using (var response = request.GetResponse())
{
// your code here...
}
}
catch (Exception exc)
{
System.Diagnostics.Debug.WriteLine(exc.Message);
}
}

Categories

Resources