-->

12/11/2011

Cookie Capturing using HttpWebRequest

In this post we will see about how cookies can be captured using HttpWebRequest class.
When ever i say some thing about Cookie, first question people ask me is...
What if Cookies are disabled by Client or User ?
Ok! Let me ask you the same. Be genuine and don't search in Google now.
Tell me steps for how to disable the cookies in IE or Firefox?
I bet half of us don't remember how to disable them.
Being Technical persons, if we can't do that, how a client / user will do that.

If you still  stick to the same, let me tell you not only mine, even your web application won't work in his machine. That is for sure.
Why?

Because, even .Net frame work uses Cookies for maintaining its asp.net session id on client side.
Now lets see a real time example:
When you open You tube, and you like to share any Video, you will see the below display for sharing.
When you click on Facebook button, some times you can directly post it to your profile, some times it will ask to enter your credentials. Automatic posting to your FB is done based on FB Cookie values reside in your local machine. Clear all cookies and then try to share from you tube, it will ask for credentials.
One more example is FB itself. When you hit FB page ponce, it will allow automatic login from next time. This is also done based up on FB Cookie values saved on your local machine.


You can access cookies already created with in your system.
What if i have to load cookies from other application and use them in my application?
Our solution comes into picture in this scenario.
When you enter a URL in browser and hit enter, that action will trigger a HttpRequest to server. Server will process the request and will send appropriate Response. This response can even contain cookies.

Our objective is doing all these things programatically with out hitting the actual page(Cookie generator).
For this we use WebHttpRequest & WebHttpResponse objects.
For demonstration of this, i created 2 web applications hosted in IIS.
App 1: Cookie creator.
App 2: Get Cookie

Step 1: Create App1, a simple web application hosted in IIS and include the below code of creating cookies.
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CreateCookie("Name", "Pratap");
        CreateCookie("Age", "27");
        CreateCookie("City", "Hyderabad");
        CreateCookie("State", "AP");
        CreateCookie("Country", "India");       
    }
    public void CreateCookie(string name, string val)
    {
        HttpCookie cookie = new HttpCookie(name);
        cookie.Value = val;
        Response.Cookies.Add(cookie);
    }
}

Step 2: Create App2, which will be using to below code to achieve our objective.
namespace TestGetCoockie
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {            
             CookieContainer cookieJar = new CookieContainer();
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/TestCookieCreator/Default.aspx");                
                request.CookieContainer = cookieJar;
                request.UseDefaultCredentials = true;                
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                foreach (System.Net.Cookie ck in response.Cookies)
                {
                    Response.Write("Cookie Name: " + ck.Name +"   Cookie Value: " + ck.Value.ToString()+"");
                }
            }
            catch (Exception ex)
            {
            }
           
        }
    }
}
First Yellow part will be used to declare the WebHttpRequest, and the following lines will add the required attributes to the request.
Second yellow line shows how the response was captured into WebHttpResponse object.
Then follows the code to display.
Out Put:
If you look at App1 code, all these cookie values are created in App1's Default page.
Thus using App2 code, we can access the cookie values without hitting/loading the page.

As every approach has pros and cons. We have a catch here.
Lets say, we are trying to load Cookies from App2's Page1(has Cookies). But the page load of Page1 is redirecting to Page2(No Cookies). Now even if you want to load Page1, you will get response of Page2 and you get nothing.

Is it helpful for you? Kindly let me know your comments / Questions.

1 comment: