I have a site programmed in PHP with login and I'm making a desktop application (Windows) and I'm trying to login to it from those system on the web.
My system in PHP works as follows: it creates a session in PHP and stores session-relevant data in a Cookie. The authorization system has 4 returns: 1, when login is successful, -1 when the password is incorrect, -2 when the user is incorrect, and -3 when the user misses the password more than 5 times in less than 1 hour (anti Brute Force).
I've got a code that searches the web (I'm going to be owed the references, it's been a while since I found it) and it's functional: if I try to log into my site with my credentials, the return is 1, returns are correct as well.
The big problem is to be able to "handle" this session. When we close the browser for example, I will be logged in when I open it because Cookie will be "holding" the session. To do this test, I created a page logged.php
, and basically the return is 'Logged' for when it is logged in and the opposite if not.
In the browser, it works normally, already in my program I'm always logged off!
Here is my method login()
, responsible for all the work:
private void login()
{
string formUrl = "http://exemplo.com.br/auth.php";
string formParams = string.Format("username={0}&password={1}", username.Text, password.Text);
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
MessageBox.Show(cookieHeader);
string pageSource;
string getUrl = "http://exemplo.com.br/logged.php";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
MessageBox.Show(pageSource);
}
}
I have some other sub-questions like: Is this safe? What would be the best way to do the returns and add data? Is using a POST / GET for a page with a SELECT in MySQL? But we'll leave it for later!