HTTPロケーションヘッダー、HttpWebRequest / Response、およびResponse.Cookies.Add()を使用して、フォーム認証を使用する認証済みページにユーザーをリダイレクトします

StackOverflow https://stackoverflow.com/questions/1436252

質問

フォーム認証を使用してサイトで認証を行い、セッション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を使用して、ブラウザから送信されたリクエストをスニッフィングできます。

コードからわかることの1つは、Cookieを明示的に追加していることです。これをしてはいけません。リクエストにCookieContainerを設定して、Cookieがすべてのリクエストとともにそのサイトに送信されるようにする必要があります。

役立つことを願っています。

他のヒント

FormsAuthenticationの使用に関する問題 クラス?特に、次のシーケンス(またはそのバリエーション)を試しましたか:

FormsAuthentication。 認証 ();

FormsAuthentication。 SetAuthCookie ();

FormsAuthentication。 RedirectFromLoginPage ();

私は、リモートWebアプリの認証済みページにリクエストを行う必要があると考えています。

有効なセッションを得るには、提供されるCookieを取得する必要があります。 aspnetセッションIDはCookieで渡されます。次に、有効な認証済みセッションを使用できるように、受け取ったCookieとともにそのアプリに必要なユーザー名とパスワードを渡す必要があります。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top