使用HTTP Location Header,HttpWebRequest / Response和Response.Cookies.Add()将用户重定向到使用表单身份验证的经过身份验证的页面
-
07-07-2019 - |
题
我需要使用表单身份验证在网站上进行身份验证,然后将用户与会话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);
}
}
解决方案
在Mozilla Firefox上使用Firebug,查看登录webapp时浏览器的确切功能。然后通过代码模拟相同的序列。
或者,您可以使用wireshark来嗅探浏览器发送的请求。
我可以从您的代码中看到的一件事是您明确添加了cookie。你不应该这样做。您应该在请求中设置CookieContainer,以便将cookie与所有请求一起发送到该站点。
希望有所帮助。其他提示
使用 FormsAuthentication有什么问题
课程?特别是,您是否尝试过以下序列(或其变体):
FormsAuthentication。
<代码>身份验证代码> <代码>(); 代码>
FormsAuthentication。
<代码> SetAuthCookie 代码> <代码>(); 代码>
FormsAuthentication。
<代码> RedirectFromLoginPage 代码> <代码>(); 代码>
我相信你必须对远程网络应用程序上经过身份验证的页面发出请求。
你必须抓住它给你的cookie才能有一个有效的会话。 aspnet会话ID在cookie中传递。然后,您需要传递该应用程序所需的用户名和密码以及您收到的cookie,以便您拥有有效的经过身份验证的会话。
不隶属于 StackOverflow