2

我需要使用表单身份验证在站点上进行身份验证,然后将用户与会话 cookie 一起重定向到该站点。我还没有弄清楚如何成功地做到这一点。到目前为止,这是我的代码。我仍然被重定向到该应用程序登录页面。任何帮助深表感谢!


protected void Button1_Click(object sender, EventArgs e)
{
 string data = "nickname=&login={0}&password={1}&action_login.x=70&action_login.y=14action_login=Login";
 string postdata = String.Format(data, "test", "test");
 string page = @"http://1.1.1.1/home.asp";
 string loginPage = @"http://1.1.1.1/auth.asp";
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginPage);
 request.Method = "POST";
 request.ContentType = "application/x-www-form-urlencoded";
 request.AllowAutoRedirect = false;
 ASCIIEncoding encoding = new ASCIIEncoding(); //encoder
 byte[] requestData = encoding.GetBytes(postdata); //encode post data
 request.ContentLength = requestData.Length;
 //write the post data to the request
 Stream requestStream = request.GetRequestStream();
 // Send the data.
 requestStream.Write(requestData, 0, requestData.Length);
 requestStream.Close();
 try
 {
  HttpWebResponse response = (HttpWebResponse) request.GetResponse();
  string cookieHeader = response.GetResponseHeader("Set-Cookie");
  string cookieValue = cookieHeader.Replace("pp_session_id=", "");
  HttpCookie cookie = new HttpCookie("pp_session_id",cookieValue);
  cookie.Domain = "1.1.1.1";
  cookie.Path = "/";
  Response.Clear();
  Response.StatusCode = 302;
  //Response.AddHeader("Set-Cookie", cookieHeader);
  Response.AddHeader("Location",page);
  Response.RedirectLocation = page;
  Response.Cookies.Add(cookie);
  Response.Flush();

 }
 catch (WebException ex)
 {
  Response.Write(ex.Message);
 }
}
4

3 回答 3

1

使用FormsAuthentication类有什么问题?特别是,您是否尝试过以下顺序(或其变体):

FormsAuthentication.Authenticate();

FormsAuthentication.SetAuthCookie();

FormsAuthentication.RedirectFromLoginPage();

于 2009-09-17T01:12:13.733 回答
1

在 Mozilla Firefox 上使用 Firebug 来查看浏览器在登录到 webapp 时究竟做了什么。然后通过代码模拟相同的序列。

或者,您可以使用wireshark 来嗅探浏览器发送的请求。

我可以从您的代码中看到的一件事是,您正在显式添加 cookie。你不应该这样做。您应该在请求上设置一个 CookieContainer,以便将 cookie 与所有请求一起发送到该站点。

希望有帮助。

于 2009-09-17T01:29:05.793 回答
0

我相信您必须向远程 Web 应用程序上的经过身份验证的页面发出请求。

你必须抓住它给你的cookie,这样你就有一个有效的会话。aspnet 会话 ID 在 cookie 中传递。然后,您需要将该应用程序所需的用户名和密码连同您收到的 cookie 一起传递,这样您将拥有一个有效的经过身份验证的会话。

于 2009-12-03T04:58:21.707 回答