C# post requests not identified as session - c#

I've been trying to have a WPF client connecting to a PHP server, logging itself in and fetching 'IsLogged.php' to validate that the client is logged in. However, 'IsLogged.php' always returns that the client isn't authenticated, what am I doing wrong?
Servercode:
"CreateAccount.php"
session_start();
if (isset($_POST['user']))
{
$_SESSION['UserName'] = $_POST['user'];
echo "check";
}
"IsLogged.php"
session_start();
if (isset($_SESSION['UserName']))
{
echo "allowed";
}
else
{
echo "not allowed";
}
Client code:
"Post" method
public static string Post(string RequestName, string PostData, out HttpStatusCode ReturnCode)
{
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
WebRequest Request = WebRequest.Create(ChatAPI.Settings.BaseUrl + RequestName);
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = Request.GetResponse();
dataStream = response.GetResponseStream();
ReturnCode = ((HttpWebResponse)response).StatusCode;
StreamReader reader = new StreamReader(dataStream);
string returnedData = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return returnedData;
}
And finally the window triggering the POST requests.
HttpStatusCode Code;
MessageBox.Show(General.Post("IsLogged", "", out Code)); --> Not allowed (intended)
MessageBox.Show(General.Post("CreateAccount", "user=jan", out Code)); --> check (intended)
MessageBox.Show(General.Post("IsLogged", "", out Code)); --> Not allowed (should be allowed)
Why is the server not registering the requests as a session?

The way the server identifies the client (and the corresponding session state) is through cookies.
Basically, in the CreateAccount request, the server attaches a cookie to its response and expects the client to present the cookie on every subsequent request.
If the cookie is not present in a request, the server has no way of identifying the client and treats the request as coming from an unknown source.
Your code does not manage cookies at all, so this is why the C# client always appears to be a new client to the PHP server.
The easiest way to save the cookie received from the server and present it on every new request is to use an instance of CookieContainer and attach it to every request you make.
I didn't try this code, so I'm not 100% sure of the syntax, but here's a starting point:
// this instance will be reused across multiple requests
private static CookieContainer cookieContainer = new CookieContainer();
public static string Post(string RequestName, string PostData, out HttpStatusCode ReturnCode)
{
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
WebRequest Request = WebRequest.Create(ChatAPI.Settings.BaseUrl + RequestName);
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
Request.ContentLength = byteArray.Length;
Request.CookieContainer = cookieContainer; // this line is new
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = Request.GetResponse();
dataStream = response.GetResponseStream();
ReturnCode = ((HttpWebResponse)response).StatusCode;
StreamReader reader = new StreamReader(dataStream);
string returnedData = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return returnedData;
}

Related

(400) Bad Request, can't get response (Custom minecraft launcher)

I just can't seem to be able to post a JSON to the webpage https://authserver.mojang.com/authenticate and get a response.
when I post the JSON it just says
The remote server returned an error: (400) Bad Request
I've gone through many different scripts by others and created my own by converting the Java code to C#. Anyway, here's the code that has worked the best so far.
string authserver = "https://authserver.mojang.com/authenticate";
byte[] rawData = fs.GetBytes(**[JSON]**);
WebRequest request = WebRequest.Create(authserver);
request.ContentType = "application/json";
request.Method = "POST";
//request.ContentLength = rawData.LongLength;
WebResponse connection = request.GetResponse();
connection.ContentType = "application/json";
connection.ContentLength = rawData.LongLength;
Stream stream = connection.GetResponseStream();
stream.Write(rawData, 0, rawData.Length);
stream.Flush();
byte[] rawVerification = new byte[10000];
int count = stream.Read(rawVerification, 0, 10000);
Edit:
is it possible to do this code with webclient?
Edit:
it had an invalid input, the json didn't have the correct data needed
try this:
WebRequest request = WebRequest.Create (authserver);
request.Method = "POST";
string postData = "YourJSON";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
using(Stream s = request.GetRequestStream ()){
s.Write (byteArray, 0, byteArray.Length);
}
WebResponse response = request.GetResponse ();
using(var dataStream = response.GetResponseStream ()){
using(StreamReader reader = new StreamReader (dataStream)){
string responseFromServer = reader.ReadToEnd ();
}
}
response.Close();
Essentially You shouldn't call getResponse() before you submit your data

How do I store a cookie after login

I'm trying to sign in to a website. It should be done by a POST request. But i need to store the cookie somehow.
My actual code:
public void botLogin(string userName, string passWord)
{
ASCIIEncoding encoding = new ASCIIEncoding();
string post_data = "username=" + userName + "&password=" + passWord;
byte[] data = encoding.GetBytes(post_data);
var requestUri = "http://registration.zwinky.com/registration/loginAjax.jhtml";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
var sharedCookies = new CookieContainer();
request.CookieContainer = sharedCookies;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
MessageBox.Show(sr.ReadToEnd());
sr.Close();
stream.Close();
}
How would i store the cookie now to use it for other requests?
First of all, cast the created WebRequest to HttpWebRequest. This will give you access to more HTTP-specific properties and methods.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
Define a CookieContainer object at the application level and set that for each created request.
request.CookieContainer = sharedCookies;
I'm pretty sure, the HttpWebRequest object will store the cookies after the download so that the next request can use them. If that still doesn't work, examine the HttpWebResponse object for cookies (again, don't forget to cast the response object to that).

post request with C# using http and .NET 5.0

http://i.stack.imgur.com/hDpwl.jpg
I need a code snipped which I can use in a WPF application. It should send a post request to the server and return a JSON. Best would be if its working same as the print screen from chrome add-on postman above. I tried to use uploading form Data with HttpClient and uploading form data with WebRequest and it returned HTML page with an error.
Thanks all
public string PostJson(string url,string json)
{
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(json);
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.Writeline(string.Format("Request {0} Response Code {1} Resonse Status Description {2} Response From Server {3}",
json, ((HttpWebResponse)response).StatusCode,
((HttpWebResponse)response).StatusDescription, responseFromServer));
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}

Web Site Redirecting Twice

I am trying to login a website with c# , I succedd to login with sending username and password, I also opened auto redirecting property of request but web server needs 2 redirection in order to enter welcome page but in my code it can only redirects once. How can I get final directed page? Any help would be appreciated.
HttpWebRequest request =(HttpWebRequest)WebRequest.Create("http://website.com/client/patronlogin.loginpageform/DEFAULT");
request.AllowAutoRedirect = true; // IMPORTANT
request.Method = "POST";
int pass = sfsdf1;
int no = dsfsdfdf0;
String formContent = "t%3Aac=%24002f%24002ftreblead.com%24002fclient%24002fdefault%24002fsearch%24002faccount%24003f&t%3Aformdata=H4sIAAAAAAAAAJWQv0oDQRDGx4NAMJ1gEURstN2zMI02BkEQDgkc1mFvb7xs2Ntdd%2FZMbKx8CRufQKz0CVLY%2BQ4%2BgI2FlYV7J6Lg%2F274mJnv932XD9CarMAyIXdiFA%2B4d0YnppB6czysCJ3mJZKDnnEF45aLETLPLZJ3Jz0mjEMlM5ZxQtbPgsiF35Wo8tUUfWXXDmad%2B8Xb5wjmEugIo8N3tR8%2BelhIxvyYx4rrIk69k7rYmloP8%2B%2Buf8Hq%2Fxdr4IxAorTKSkkkjZ5d5RuHTxd3EcDUfmtpOdHEuJyO4BSgwXyTfr2pT1qTJeh%2BsUU1hw9Btn8MIkxpjUbtiTXk%2FnOO8%2FSxe3N9thNBlEBbKBm29xrvunpUWAahrr6R6qrbr%2BbD9Q%2FjCx9ggTUPAgAA&j_username="+no.ToString()+"&j_password="+pass.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(formContent);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
// Get the response ...
WebResponse response;
response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
richTextBox1.AppendText(reader.ReadToEnd());
richTextBox1.AppendText(HttpUtility.UrlDecode(reader.ReadToEnd()));
reader.Close();
dataStream.Close();
response.Close();
Could it be that you need to set MaximumAutomaticRedirections property to a higher value?

This property cannot be set after writing has started! on a C# WebRequest Object

I want to reuse a WebRequest object so that cookies and session would be saved for later request to the server. Below is my code. If i use Post function twice on the second time at
request.ContentLength = byteArray.Length;
it will throw an exception
This property cannot be set after writing has started!
But as you can see
dataStream.Close();
Should close the writing process! Anybody knows what's going on?
static WebRequest request;
public MainForm()
{
request = WebRequest.Create("http://localhost/admin/admin.php");
}
static string Post(string url, string data)
{
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(data);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
request.Abort();
return responseFromServer;
}
You cannot reuse the WebRequest. Take the returned HttpWebResponse.Cookies, construct a new WebRequest and fill the HttpWebRequest.CookieContainer. (You need to assign a CookieContainer in the first request to get Cookies returned.)

Categories