C# WebRequest using Cookies - c#

I have a winforms application i have been working on that runs multiple tests on consumer accounts. The tests require a one time login in order to execute.
string paramaters = "authmethod=on&chkRememberMe=on&login-form-type=pwd&password=" + pw.Text + "&userid=" + uid.Text + "&username=" + uid.Text;
string strResponse;
HttpWebRequest requestLogin = (HttpWebRequest)WebRequest.Create("https://www.url.com/login.form");
requestLogin.Method = "POST";
requestLogin.CookieContainer = cookieJar;
requestLogin.ContentType = "application/x-www-form-urlencoded";
requestLogin.ContentLength = paramaters.Length;
StreamWriter stOut = new StreamWriter(requestLogin.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(paramaters);
stOut.Close();
StreamReader stIn = new StreamReader(requestLogin.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
This script works for the login just fine, the problem is when i need to actually run the tests i need to return all the results into a string (HTML results).
private string runTestRequest(Uri url, string parameters)
{
string testResults = string.Empty;
HttpWebRequest runTest = (HttpWebRequest)WebRequest.Create(url);
runTest.CookieContainer = cookieJar;
runTest.Method = "POST";
runTest.ContentType = "application/x-www-form-urlencoded";
StreamWriter stOut = new StreamWriter(runTest.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(parameters);
stOut.Close();
StreamReader stIn = new StreamReader(runTest.GetResponse().GetResponseStream());
testResults = stIn.ReadToEnd();
stIn.Close();
return testResults;
}
But it goes and tries to login. How can i use the Cookie from the previous login request with this + many other web requests?
Thanks for the help.
EDIT:
I added this to my code yet which should do the same thing as BrokenGlass is saying except just a little different but still doesn't work.
foreach (Cookie cookie in responseLogin.Cookies)
{
cookieJar.Add(new Cookie(cookie.Name.Trim(), cookie.Value.Trim(), cookie.Path, cookie.Domain));
richTextBox2.Text += cookie.Name.ToString() + Environment.NewLine + cookie.Value.ToString() + Environment.NewLine + cookie.Path.ToString() + Environment.NewLine + cookie.Domain.ToString();
}

Something like this should work, I am using similar code to save a login cookie:
HttpWebRequest runTest;
//...do login request
//get cookies from response
CookieContainer myContainer = new CookieContainer();
for (int i = 0; i < Response.Cookies.Count; i++)
{
HttpCookie http_cookie = Request.Cookies[i];
Cookie cookie = new Cookie(http_cookie.Name, http_cookie.Value, http_cookie.Path);
myContainer.Add(new Uri(Request.Url.ToString()), cookie);
}
//later:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.url.com/foobar");
request.CookieContainer = myContainer;

Related

C# POST/GET Issue with Login Credentials

Pretty much a noob here, having issues here with a Post Request in C#. I am returning the server response to webBrowser Control, and no matter what I try, I just get the login page returned with no form values posted. Any help here would be greatly appreciated!
Login Page: "https://www.carrier411.com/".
URL example that I want to return:(You have to be logged in to view)
"https://www.carrier411.com/manager/companydetail.cfm?docket=MC1114638"
var username = "******"; var password = "******";
string url = "https://www.carrier411.com/manager/companydetail.cfm?docket=MC1073504";
string postData = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + passWord));
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "text/html";
httpRequest.Headers.Add("Authorization", "Basic " + postData);
httpRequest.Accept = #"text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8";
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{streamWriter.Write(postData);}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
var streamReader = new StreamReader(httpResponse.GetResponseStream());
string result = streamReader.ReadToEnd().ToString();
webBrowser1.DocumentText = result;

Windows form application wont work on another PC

I created an windows form application that goes to a website and does a HTTPwebrequest POST and then displays the result in a webbrowser. I tested it on the computer that I wrote the program on and it works exactly like it should. However when I get the .exe file from the bin folder along with htmlagilitypack.dll and run a test on another computer, it does the POST data but web page that shows up in broswer is just the default login page. I have looked at it on fiddler and it seems like the cookies aren't getting set to the webbrowser. How can I fix this? I have also compiled the program in release mode and transferred the files in the release folder and its the same result.
On the program I used this to set the cookie for the browser.
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetSetCookie(string lpszUrlName, string lpszCookieName, string lpszCookieData);
Does it have to do something with that dll file?
Edit: I have made sure both computer has 4.5 NET installed.
//get the cookie first
CookieCollection cookies = new CookieCollection();
CookieContainer cookiecontainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com" + url);
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
//get the auth token
using (StreamReader authreader = new StreamReader(request.GetResponse().GetResponseStream()))
{
source = authreader.ReadToEnd();
}
//need the auth token
string token = Regex.Match(source, "authenticity_token.+?value=\"(.+?)\"").Groups[1].Value;
//need the POST url
string action = Regex.Match(source, "UTF-8.+?action=\"(.+?)\"").Groups[1].Value;
//get the reponse from the server and save the cookies from the first request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies = response.Cookies;
response.Close();
string formparam = string.Format("utf8=%E2%9C%93&authenticity_token={0}&size={1}&commit=add to cart", token, sizechart[0]);
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com"+ action);
webreq.CookieContainer = new CookieContainer();
webreq.CookieContainer = request.CookieContainer;
//webreq.CookieContainer.Add(cookies); //recover the cookie first request
webreq.Method = "POST"; //set a POST method
webreq.Referer = "http://www.supremenewyork.com" + url;
webreq.ContentType = "application/x-www-form-urlencoded";
webreq.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";
webreq.KeepAlive = true;
webreq.AllowAutoRedirect = true;
byte[] bytes = Encoding.UTF8.GetBytes(formparam);
webreq.ContentLength = bytes.Length;
//write
Stream postdata = webreq.GetRequestStream(); //open connection
postdata.Write(bytes, 0, bytes.Length); //send the data
postdata.Close();
//get the final response from the server
HttpWebResponse resp = (HttpWebResponse)webreq.GetResponse();
cookies = resp.Cookies;
response.Close();
//Stream answer = resp.GetResponseStream();
//StreamReader _answer = new StreamReader(webreq.GetResponse().GetResponseStream());
//string reply = _answer.ReadToEnd();
//need to check if item has been added to cart
//richTextBox1.Text = reply;
//check if item has been added to cart
HttpWebRequest webreq2 = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com/shop/cart");
//webreq2.CookieContainer = new CookieContainer();
webreq2.CookieContainer = webreq.CookieContainer;
HttpWebResponse resp2 = (HttpWebResponse)webreq2.GetResponse();
Stream answer2 = resp2.GetResponseStream();
StreamReader _answer2 = new StreamReader(webreq2.GetResponse().GetResponseStream());
string reply2 = _answer2.ReadToEnd();
string item = textBoxkeyword.Text;
string color = textBoxcolor.Text.ToLower();
if(reply2.Contains(color))
{
//proceed to check out
//update user
appendtext(nDateTime + item + " " + color + " added to cart" );
appendtext(nDateTime + "Please check out the item");
HttpWebRequest webreq3 = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com/checkout");
//webreq3.CookieContainer = new CookieContainer();
webreq3.CookieContainer = webreq2.CookieContainer;
HttpWebResponse resp3 = (HttpWebResponse)webreq3.GetResponse();
//webBrowser1.ScriptErrorsSuppressed = false;
//RegistryKey RegKey = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Internet Explorer\Main", true);
//RegKey.SetValue("Display Inline Images", "yes");
string cookie_string = "";
foreach (Cookie cook in resp3.Cookies)
{
cookie_string += cook.ToString() + ";";
InternetSetCookie("http://www.supremenewyork.com/checkout", cook.Name, cook.Value);
}
webBrowser1.Navigate("http://www.supremenewyork.com/checkout");
}
Edit2: added all the code

Browse site which requires logged info

I have been trying to get it working for hours with little success. From source after first request I can see that login was successful, but using cookies to access other keeps asking for login info.
Here is site which I'm trying to access: http://gpro.net/
And here is the code I'm using:
string formUrl = "http://gpro.net/pl/Login.asp?langCode=pl&Redirect=gpro.asp"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = "textLogin=user&textPassword=pass&Logon=Login&LogonFake=Sign+in";
string strResponse;
HttpWebRequest requestLogin = (HttpWebRequest)WebRequest.Create(formUrl);
requestLogin.Method = "POST";
requestLogin.CookieContainer = cookieJar;
requestLogin.ContentType = "application/x-www-form-urlencoded";
requestLogin.ContentLength = formParams.Length;
StreamWriter stOut = new StreamWriter(requestLogin.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(formParams);
stOut.Close();
HttpWebResponse responseLogin = (HttpWebResponse)requestLogin.GetResponse();
StreamReader stIn = new StreamReader(responseLogin.GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
sb.Append(strResponse);
sb.AppendLine();
sb.AppendLine();
sb.AppendLine();
//Add cookies to CookieJar (Cookie Container)
foreach (Cookie cookie in responseLogin.Cookies)
{
cookieJar.Add(new Cookie(cookie.Name.Trim(), cookie.Value.Trim(), cookie.Path, cookie.Domain));
sb.AppendLine(cookie.Name.ToString() + Environment.NewLine + cookie.Value.ToString() + Environment.NewLine + cookie.Path.ToString() + Environment.NewLine + cookie.Domain.ToString());
}
//Grab the cookie we just got back for this specifc page
string cookies = cookieJar.GetCookieHeader(requestLogin.RequestUri);
//put it back in the cookie container for the whole server
cookieJar.SetCookies(new Uri("http://www.gpro.net/"), cookies);
string testResults = string.Empty;
HttpWebRequest runTest = (HttpWebRequest)WebRequest.Create("http://www.gpro.net/pl/RaceAnalysis.asp");
runTest.Referer = "http://gpro.net/pl/gpro.asp";
runTest.CookieContainer = cookieJar;
//runTest.Method = "POST";
//runTest.ContentType = "application/x-www-form-urlencoded";
//StreamWriter stOut2 = new StreamWriter(runTest.GetRequestStream(), System.Text.Encoding.ASCII);
//stOut2.Write(formParams);
//stOut2.Close();
StreamReader stIn2 = new StreamReader(runTest.GetResponse().GetResponseStream());
testResults = stIn2.ReadToEnd();
stIn2.Close();
sb.Append(testResults);
e.Result = sb.ToString();
I found out what was wrong with code above and every similar one posted in stack overflow (I have tried all marked as working). When I was logging with browser redirection worked fine, with but using above method my request was redirected to same address, but without www prefix. That resulted with two different cookies collections. I removed www prefix from every request which solved login problem.

HttpWebRequest work differently in debug/release

Ive a problem with a code because it work differently if I test it in Visual Studio either I test it on my site.
i am trying to do an autologin on an external web site. If I test it from VS, I am correctly redirected on the external site. From my site i obtain i am redirected to "http://www.MySite.com/cgi-bin/wbc_login/...."!!!!!
The code is the following:
private void MioMetodo(String username, String password)
{
CookieContainer Cookies = new CookieContainer();
Cookie langCookie = new Cookie("pk_lang", "\"italiano\"", "/");
langCookie.Domain = "xxx.yy";
Cookie loginCookie = new Cookie("wc_loginoslimit", "\"" + username + "\"", "/");
loginCookie.Domain = "xxx.yy";
Cookie passwordCookie = new Cookie("wc_passwordoslimit", "\"" + password + "\"", "/");
passwordCookie.Domain = "xxx.yy";
Cookies.Add(langCookie);
Cookies.Add(loginCookie);
Cookies.Add(passwordCookie);
UTF8Encoding encoding = new UTF8Encoding();
String postData = "wc_login=" + username + "&wc_password=" + password + "&limit=0&Avanti=Avanti";
Byte[] data = encoding.GetBytes(postData);
HttpWebRequest myHttpWebRequest = WebRequest.Create("http://xxx.yy/cgi-bin/wbc_login") as HttpWebRequest;
myHttpWebRequest.Method = "POST";
myHttpWebRequest.Referer = "http://xxx.yy/cgi-bin/wbc_login";
myHttpWebRequest.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
myHttpWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
myHttpWebRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4");
myHttpWebRequest.Headers.Add(HttpRequestHeader.CacheControl, "max-age=0");
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
myHttpWebRequest.CookieContainer = Cookies;
myHttpWebRequest.ContentLength = data.Length;
Stream newStream = myHttpWebRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse myHttpWebResponse = myHttpWebRequest.GetResponse() as HttpWebResponse;
StreamReader streamRead =new StreamReader(myHttpWebResponse.GetResponseStream());
Response.Write(streamRead.ReadToEnd());
streamRead.Close();
myHttpWebResponse.Close();
}
Thanx in advance

C# WebRequest Login Session

Okay I tried asking this question yesterday but i'm not sure if I gave enough info, i got an answer but it hasn't worked for me. Basically what i'm doing is the user opens this windows forms application and logs in. Afterwhich they enter some text into a textbox and click run. At this point the run function is making a webrequest to a server that requires a login (the login that is initially done after they open the program. For some reason its still not seeing that the user is logged in when performing the second request even though the cookies are added too a cookie container. I'm not sure what i'm doing wrong but I will post my code so you can further help me.
This is the function that is performed for the login when the user enters the application.
private void button1_Click(object sender, EventArgs e)
{
string paramaters = "authmethod=on&chkRememberMe=on&login-form-type=pwd&password=" + pw.Text + "&userid=" + uid.Text + "&username=" + uid.Text;
string strResponse;
HttpWebRequest requestLogin = (HttpWebRequest)WebRequest.Create("https://www.url.com/login.form");
requestLogin.Method = "POST";
requestLogin.CookieContainer = cookieJar;
requestLogin.ContentType = "application/x-www-form-urlencoded";
requestLogin.ContentLength = paramaters.Length;
StreamWriter stOut = new StreamWriter(requestLogin.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(paramaters);
stOut.Close();
HttpWebResponse responseLogin = (HttpWebResponse)requestLogin.GetResponse();
StreamReader stIn = new StreamReader(responseLogin.GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
//Add cookies to CookieJar (Cookie Container)
foreach (Cookie cookie in responseLogin.Cookies)
{
cookieJar.Add(new Cookie(cookie.Name.Trim(), cookie.Value.Trim(), cookie.Path, cookie.Domain));
richTextBox2.Text += cookie.Name.ToString() + Environment.NewLine + cookie.Value.ToString() + Environment.NewLine + cookie.Path.ToString() + Environment.NewLine + cookie.Domain.ToString();
}
if (strResponse.Contains("Log On Successful") || strResponse.Contains("already has a webseal session"))
{
foreach (Control cont in this.Controls)
{
cont.Visible = true;
}
loginPanel.SendToBack();
loginPanel.Visible = false;
}
else
{
MessageBox.Show("Login failed.");
}
}
This is the function that is ran when the user clicks the "run" button to initiate the tests on a consumer account.
private string runTestRequest(Uri url, string parameters)
{
string testResults = string.Empty;
HttpWebRequest runTest = (HttpWebRequest)WebRequest.Create(url);
runTest.CookieContainer = cookieJar;
runTest.Method = "POST";
runTest.ContentType = "application/x-www-form-urlencoded";
StreamWriter stOut = new StreamWriter(runTest.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(parameters);
stOut.Close();
StreamReader stIn = new StreamReader(runTest.GetResponse().GetResponseStream());
testResults = stIn.ReadToEnd();
stIn.Close();
return testResults;
}
And of course this is my cookie container object
public CookieContainer cookieJar = new CookieContainer();
P.S.: The domains of the webrequests are different. First being abc.com 2nd being 123.com The only problem is that the first domain (which is the login) is a global login for internal web applications like 123.com, so how would i use the login session from the 1st domain with the 2nd domain?
Can you please assist in helping me figure out what I am doing wrong.
I found out that what was happening was it was redircting to a subdomain on the same domain as the 2nd (123.com) to use the login. Evidently they had this global login system built on the multiple domains to pass the cookies. The code above DOES work and i do have it working now. Thanks!!
string url = "http://www.ABC/MemberShip/Login.aspx";// HttpContext.Current.Request.Url.AbsoluteUri.ToString().Replace("AutoLogin", "Login");
CookieContainer myCookieContainer = new CookieContainer();
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.CookieContainer = myCookieContainer;
request.Method = "GET";
request.KeepAlive = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
string srcString = reader.ReadToEnd();
// get the page ViewState
string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
int j = srcString.IndexOf("\"", i);
string viewState = srcString.Substring(i, j - i);
// get page EventValidation
string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
j = srcString.IndexOf("\"", i);
string eventValidation = srcString.Substring(i, j - i);
string submitButton = "LoginButton";
// UserName and Password
string userName = "userid";
string password = "password";
// Convert the text into the url encoding string
viewState = System.Web.HttpUtility.UrlEncode(viewState);
eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);
submitButton = System.Web.HttpUtility.UrlEncode(submitButton);
// Concat the string data which will be submit
string formatString =
"txtUserName={0}&txtPassword={1}&btnSignIn={2}&__VIEWSTATE={3}&__EVENTVALIDATION={4}";
string postString =
string.Format(formatString, userName, password, submitButton, viewState, eventValidation);
// Convert the submit string data into the byte array
byte[] postData = Encoding.ASCII.GetBytes(postString);
// Set the request parameters
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.Referer = url;
request.KeepAlive = false;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; CIBA)";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = myCookieContainer;
System.Net.Cookie ck = new System.Net.Cookie("TestCookie1", "Value of test cookie");
ck.Domain = request.RequestUri.Host;
request.CookieContainer.Add(ck);
request.CookieContainer.Add(response.Cookies);
request.ContentLength = postData.Length;
// Submit the request data
System.IO.Stream outputStream = request.GetRequestStream();
request.AllowAutoRedirect = true;
outputStream.Write(postData, 0, postData.Length);
outputStream.Close();
// Get the return data
response = request.GetResponse() as HttpWebResponse;
responseStream = response.GetResponseStream();
reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
srcString = reader.ReadToEnd();
Response.Write(srcString);
Response.End();

Categories