user613037
user613037

Reputation: 75

Reading a cookie in a different application in Asp.Net

I have an application in Asp.Net and at a click of a button it is supposed to launch another mapping application. In that application the credentials of the user like user name and Email are required. So, I was trying to set a cookie and fix the domain of the cookie to that application but I am not able to see the cookie in that application. I am not really sure what is going wrong or if I have made some mistake in the cookie.

         MembershipUser usr = Membership.GetUser();
    Guid newUserId = (Guid)usr.ProviderUserKey;
    HttpCookie SampleCookie = new HttpCookie("UserInfo");
    Response.Cookies["UserInfo"]["UserName"] = usr.UserName;
    Response.Cookies["UserInfo"]["Email"] = usr.Email;
    SampleCookie.Expires = DateTime.Now.AddDays(1);
    Response.Cookies.Add(SampleCookie);
    SampleCookie.Domain = "http://157.182.212.204/MAP";

Thank you once again for the help.

Code for MAP application:

          function Get_Cookie( check_name ) {
            // first we'll split this cookie up into name/value pairs
            // note: document.cookie only returns name=value, not the other components

            var a_all_cookies = document.cookie.split( ';' );
            var a_temp_cookie = '';
            var cookie_name = '';
            var cookie_value = '';
            var b_cookie_found = false; // set boolean t/f default f

            for ( i = 0; i < a_all_cookies.length; i++ )
            {
                // now we'll split apart each name=value pair
                a_temp_cookie = a_all_cookies[i].split( '=' );


                // and trim left/right whitespace while we're at it
                cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

                // if the extracted name matches passed check_name
                if ( cookie_name == check_name )
                {
                    b_cookie_found = true;
                    // we need to handle case where cookie has no value but exists (no = sign, that is):
                    if ( a_temp_cookie.length > 1 )
                    {
                        cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
                    }
                    // note that in cases where cookie is initialized but no value, null is returned
                    return cookie_value;
                    break;
                }
                a_temp_cookie = null;
                cookie_name = '';
            }
            if ( !b_cookie_found )
            {
                return null;
            }
        }

        function Delete_Cookie( name, path, domain ) {
            if ( Get_Cookie( name ) ) document.cookie = name + "=" +
                    ( ( path ) ? ";path=" + path : "") +
                    ( ( domain ) ? ";domain=" + domain : "" ) +
                    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
        }

                    alert(Get_Cookie("UserName"));                                                        

The code for the WVWRAPICt page RESET.aspx.cs is given below...This is where the cookie is being set

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
  public partial class RESET_RESET : System.Web.UI.Page
  {
protected void Page_Load(object sender, EventArgs e)
{
            Menu Nav = Master.FindControl("NavigationMenu1") as Menu;
    MenuItemCollection Menu = Nav.Items;
    foreach (MenuItem item in Menu)
    {
        string name = item.Text.ToString();
        if (name == "ADMIN")
        {
            item.Enabled = User.IsInRole("Administrator");
        }
        if (name == "ICT")
        {
            item.Selected = true;
        }
        else
        {
            item.Selected = false;
        }
    }
}

protected void Button2_Click(object sender, EventArgs e)
{
    MembershipUser usr = Membership.GetUser();
    Guid newUserId = (Guid)usr.ProviderUserKey;
    HttpCookie SampleCookie = new HttpCookie("UserInfo");
    SampleCookie["UserName"] = usr.UserName;
    SampleCookie["Email"] = usr.Email;
    string connectionString =
  ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

    string checkSiteEventIDSQL = "Select * from UserProfiles WHERE UserId='" + newUserId + "'";

    using (SqlConnection myConnection1 = new SqlConnection(connectionString))
    {
        try
        {
            myConnection1.Open();
            SqlCommand myCommand1 = new SqlCommand(checkSiteEventIDSQL, myConnection1);
            SqlDataReader myReader = myCommand1.ExecuteReader();
            if (myReader.HasRows)
            {
                while (myReader.Read())
                {
                    string Agency = (myReader.GetValue(2)).ToString();
                    SampleCookie["Agency"] = Agency;

                }


            }
        }
        catch (Exception ex)
        {

        }
        finally
        {
            myConnection1.Close();
        }
    }
    SampleCookie.Expires = DateTime.Now.AddDays(1);
     SampleCookie.Domain = "157.182.212.204/MAP";
    // SampleCookie.Path = "/MAP";
    Response.Cookies.Add(SampleCookie);

   Response.Redirect("http://157.182.212.204/MAP/index.html");
}
}

Upvotes: 3

Views: 3136

Answers (1)

John Hoven
John Hoven

Reputation: 4085

Regarding trouble with the way you are setting your cookie... you're not going to find the cookie in the response unless you've added it to the response. (And if you ARE finding it, you're just over-writing that cookie a couple lines later). Just edit the cookie directly then add to the cookie jar. Also I believe the MAP should be in the path property of the cookie (not sure how big of a difference it makes). As far as I know you don't want the http in the domain (again, not sure if the browser is smart enough to handle).

MembershipUser usr = Membership.GetUser();
    Guid newUserId = (Guid)usr.ProviderUserKey;
    HttpCookie sampleCookie = new HttpCookie("UserInfo");
    sampleCookie["UserName"] = usr.UserName;
    sampleCookie["Email"] = usr.Email;
    sampleCookie.Expires = DateTime.Now.AddDays(1);
    sampleCookie.Domain = "157.182.212.204";
    sampleCookie.Path = "/MAP";
    Response.Cookies.Add(sampleCookie);

Cookies can only be set to a domain which is a 'tail' of the current FQDN. So if your current FQDN is not 157.182.212.204, the cookie will not set in the browser. By tail, for example, I mean http://overflow.acme.com could set a cookie for overflow.acme.com or acme.com, but not for fubar.acme.com or fubar.com.

My guess is if your application is on a different FQDN than the MAP application, you're going to need to figure a different way to pass the user name and e-mail to the map application (maybe post to a page on the map application which can set the cookie and then redirect to the appropriate page?


Update after you've posted some more code:

Try this:

   SampleCookie.Domain = "157.182.212.204";
   SampleCookie.Path = "/MAP";
   Response.Cookies.Add(SampleCookie);

   Response.Redirect("http://157.182.212.204/MAP/index.html", false);

Setting false on the response.redirect should cause the set cookie headers to come through. You might need to short circuit other logic in your page if you have anything in the render events

Or just pass the stuff in a query string. You're not using HttpOnly cookies (so a user could inject the cookies).

Upvotes: 1

Related Questions