Sometimes we come across integration scenario's that look straighforward, but where the devil is in the details. We needed to integrate our asp.net/silverlight application in an existing ASP "classic" site (yes, the still exist). The catch was that we needed to call the ASP "classic" site in a server to server call to get some information, but we needed to do this under the context of the current user. You may be wondering why we didn't go through a shared database or someting, but the problem is that there is little knowledge left of the old app, so changing the existing app was a no go.
So, in order to impersonate the user, you need your server-sided request look like that user. This means forwarding the cookies the user sends, and sending back the cookies the server sends to the user. Below is code that demonstrates that.
HttpWebRequest webRequestToServer = (HttpWebRequest)HttpWebRequest.Create("http://somedomain/somepage.asp"); webRequestToServer.CookieContainer = new CookieContainer(); foreach (String cookieKey in Request.Cookies) { HttpCookie cookie = Request.Cookies[cookieKey]; Cookie serverCookie = new Cookie(cookie.Name, cookie.Value, "/", "somedomain"); webRequestToServer.CookieContainer.Add(serverCookie); } HttpWebResponse webResponseFromServer = (HttpWebResponse)webRequestToServer.GetResponse(); foreach (Cookie serverCookie in webResponseFromServer.Cookies) { HttpCookie clientCookie = Response.Cookies[serverCookie.Name]; if (clientCookie == null) { clientCookie = new HttpCookie(serverCookie.Name); } clientCookie.Value = serverCookie.Value; clientCookie.Expires = serverCookie.Expires; Response.Cookies.Add(clientCookie); } webResponseFromServer.Close();
This code works fine in a test environment, but there is a catch... in some cases the domain of the server is not set in the cookie you get on the server side. The problem with that is that when you set the domain, it doesn't correspond to what the server expects. You can see this if you write out the cookies you send/receive (both on the browser connection and te server-server connection) to a log or something (including the domain. It took a while to figure out, but replacing "somedomain" with Request.ServerVariables["LOCAL_ADDR"] did the trick.
Remember Me
a@href@title, strike
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.