开发者

Writing cookies from CookieContainer to the IE cookie store

开发者 https://www.devze.com 2023-01-15 21:32 出处:网络
I want to navigate to a page in a web app from a desktop app. \"No problem\", I hear you say, \"just fire up the default browser with the correct URL\". However, the web app uses ASP.NET Forms Authent

I want to navigate to a page in a web app from a desktop app. "No problem", I hear you say, "just fire up the default browser with the correct URL". However, the web app uses ASP.NET Forms Authentication, and the users don't want to see the login page because they have already authenticated with the same credentials in the desktop app.

That sounds simple enough, all I have to do is emit an HTTP POST from the desktop app with that fakes the postback from the web app's login page. The web app will then set its authentication ticket and session state cookies, return them to me, and I will store them in the IE cookie store. I can then navigate to the desired page and the web app will think that it's already authenticated.

I have some working code that constructs the HTTP POST, sends it off, and gets a valid response containing the right cookies. However, I can't see how to write them into the IE cookie store. Can anyone point me in the right direction?

Sample code:

var requestUrl = Properties.Settings.Default.WebsiteLoginPageUrl;

var requestEncoding = Encoding.GetEncoding(1252);

// Simulated login postdata
var requestText = string.Format(
    "__VIEWSTATE={2}&__EVENTTARGET={3}&__EVENTARGUMENT={4}&__EVENTVALIDATION={5}&userNameText={0}&passwordText={1}&submitButton=Log+In",
    HttpUtility.UrlEncode(Properties.Settings.Default.UserName),
    HttpUtility.UrlEncode(Properties.Settings.Default.Password),
    Properties.Settings.Default.FakeViewState,
    Properties.Settings.Default.FakeEventTarget,
    Properties.Settings.Default.FakeEventArgument,
    Properties.Settings.Default.FakeEventValidation);

var request = (HttpWebRequest) WebRequest.Create(requestUrl);
request.Method = "POST";
request.Accept = "*/*";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = requestEncoding.GetByteCount(requestText);
request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
request.AllowAutoRedirect = false;
request.KeepAlive = false;
request.CookieContainer = new CookieContainer();

using(var writer = new StreamWriter(request.GetRequestStream(), requestEncoding)) {
    writer.Write(requestText);
}

var response = (HttpWebResponse) request.GetResponse();

// TODO: Grab the response cookies and save them to the interactive desktop user's cookie store.

Process.Start(new ProcessStartInfo {
    Fi开发者_如何学GoleName = Properties.Settings.Default.WebsiteTargetPageUrl,
    UseShellExecute = true,
});


You need to call the unmanaged InternetSetCookie() function. And look! Someone wrote the interop for you already. You should verify its correctness though.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号