3
I have a site programmed in PHP with login and I’m making a desktop application (Windows) and I’m trying to log in to it from these system on the web.
My system in PHP works as follows: it creates a session in PHP and stores the session-relevant data in a cookie. The authorization system has 4 returns: 1, when there is success when logging in, -1 when the password is incorrect, -2 when the user is incorrect and finally, -3 when the user misses the password more than 5 times in less than 1 hour (anti Brute Force).
I got a code searching on the web (I’ll be owing references, I found it for a while) and it is functional: if I try to log in to my site with my credentials, the return is 1, if there is any error, the returns are correct too.
The big problem is getting "hold" on this session. When we close the browser for example, I will be logged in when I open because the Cookie will be "holding" the session. To do this test, I created a page logged.php
, and basically the return is 'Logged in' for when you are logged in and otherwise.
In the browser, it works normally, already in my program I am always logged!
Just follow 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 doing this safe? What would be the best way to make the returns and add data? Would it be using a POST/GET for a page with a SELECT in Mysql? But we leave it for later!
I think it would make it a lot easier for you to have a separate API for desktop software instead of the traditional login.
– Bacco