C# WebRequest Login Session

2019-05-07 01:55发布

问题:

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.

回答1:

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!!



回答2:

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();