Cookies?

Rate It (1)

Last post 11-03-2006 12:02 PM by vivek_iit. 16 replies.

Sort Posts:

  • Confused [8-)] Cookies?

    09-27-2006, 2:01 AM
    • Participant
      961 point Participant
    • RN5A
    • Member since 07-13-2006, 7:59 PM
    • Mumbai, India
    • Posts 406
    A web.config file has the following code:

    <configuration>
        <system.web>
            <authentication mode="Forms">
                <forms name="NETConnectCookie" loginUrl="Login.aspx">
                    <credentials passwordFormat="SHA1"/>
                </forms>
            </authentication>
        </system.web>

        <location path=".">
            <system.web>
                <authorization>
                    <deny users="?"/>
                </authorization>
            </system.web>
        </location>
    </configuration>


    Assuming that the local m/c does not have the cookie named NETConnectCookie, the above code ensures that if a user tries to navigate to any ASPX files in the directory that the above web.config file exists in, then the user will be first redirected to Login.aspx. Assume that the directory in which the above web.config file exists has a ASPX file named Products.aspx.

    When a user tries to navigate to Products.aspx without logging in, web.config directs him to Login.aspx. Assume that a user with the username bobby is a valid user (which I am validating against a SQL Server 2005 DB table). This is how I tried it (this is the code in Login.aspx which communicates with web.config when the user directly tries to navigate to Products.aspx without logging in):

    <script runat="server">
        Sub LoginUser(ByVal obj As Object, ByVal ea As EventArgs)
            ..........
            ..........
            'user has been validated; so take him to Products.aspx
            FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, True)
            Response.Cookies("NETConnectCookie"("UserName") = txtUserName.Text
        End Sub
    </script>


    This does create the persistent cookie named NETConnectCookie which when opened, also shows the text UserName=bobby but the user doesn't get redirected to Products.aspx though he has been logged in successfully. In fact, the user remains at Login.aspx with the URL getting appended by the querystring ReturnUrl=Products.aspx. Why isn't the user getting redirected to Products.aspx after successfully logging in? Note that if I remove the Response.Cookies line in Login.aspx, then the user gets redirected to Products.aspx after logging in.

    There's another problem. Next suppose the user closes the browser window which he had used to log in. He opens a new browser window & navigates to Products.aspx. Under such circumstances, I want to show him a welcome message with his username in Products.aspx without taking him to Login.aspx since the cookie NETConnectCookie is a persistent cookie but the user still gets directed to Login.aspx. Why? This is the code in Products.aspx:

    <script runat="server">
        Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
            Response.Write("Welcome " & Request.Cookies("NETConnectCookie")("UserName"))
        End Sub
    </script>


    If I change the name of the cookie to, say, 'Details', in Login.aspx i.e.

    Response.Cookies("Details")("UserName") = txtUserName.Text

    & make the corresponding change in Products.aspx, then after successfully logging in Login.aspx, the user is taken to Products.aspx which shows the message

    Welcome bobby

    But when the user closes this window, opens a new browser window & navigates to Products.aspx, then, as expected, the user is not taken to Login.aspx but Products.aspx generates this error:

    Object reference not set to an instance of an object.

    pointing to the Response.Write line in Products.aspx! When I open the cookie from the Temporary Internet Files folder, this time the cookie doesn't show the text UserName=bobby! Why?

    What's the difference between a normal cookie & a cookie created by the FormsAuthentication object?
    Thanks

    RON
    *********
    If you have an apple & I have an apple & we exchange our apples, then each of us will still have only 1 apple but if you have an idea & I have an idea & we exchange our ideas, then each of us will have 2 ideas
  • Re: Cookies?

    09-27-2006, 3:09 PM
    • All-Star
      17,710 point All-Star
    • vivek_iit
    • Member since 06-18-2006, 2:13 PM
    • New Delhi
    • Posts 3,171
    • TrustedFriends-MVPs

    Hello,

    I recently posted some info in my blog on this topic which you might find useful: http://geekswithblogs.net/vivek/archive/2006/09/14/91191.aspx

    Hope this helps,

    Vivek

  • Re: Cookies?

    09-29-2006, 4:53 AM
    • Participant
      961 point Participant
    • RN5A
    • Member since 07-13-2006, 7:59 PM
    • Mumbai, India
    • Posts 406
    Thanks, Vivek, your aticle has indeed turned out to be very useful but I have encountered another problem. Keeping the web.config file shown in post #1 as it is, I am adding the following setting so that any user can access HomePage.aspx:

    <location path="HomePage.aspx">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>

    Suppose a user comes to HomePage.aspx. From the home page, he tries to navigate to another ASPX page, say, MyPage.aspx by clicking a link in the home page. But the web.config file redirects the user to Login.aspx. Assuming that the user has been validated successfully, he is then directed to MyPage.aspx. Also assume that the username of the user is bobby. When this user finally goes to MyPage.aspx, I want to display a welcome message to him with his username i.e. MyPage.aspx should display Welcome bobby. To get the username in MyPage.aspx, I am using the Name & Value properties of the HttpCookie object in Login.aspx. This is the code in Login.aspx:


    Sub LoginUser(obj As Object, ea As EventArgs)
       
    'after successful login
            Dim hCookie As HttpCookie

        FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, True)
        hCookie = FormsAuthentication.GetAuthCookie(txtUserName.Text, True)

             hCookie.Name = "MyCookie"
        hCookie.Value = txtUserName.Text

             hCookie.Expires = DateTime.Now.AddMinutes(2)
        Response.Cookies.Add(hCookie)
    End Sub


    This is the simple code in MyPage.aspx:

    Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
        lblMessage.Text = "Welcome " & Request.Cookies("MyCookie").Value
    End Sub


    When this user finally comes to MyPage.aspx, he is shown the message

    Welcome bobby

    Note that in Login.aspx, I have set the cookie to expire after 2 minutes which means that the user sees the welcome message along with his username if he closes the browser he used to login & opens a new browser within the next 2 minutes. But when I go to the Temporary Internet Files folder & click the cookie, I find that the cookie has been set to expire after 30 minutes though I have set it to expire after 2 minutes. Why so?

    What I found is if I get rid of the 2 red lines in Login.aspx, then the cookie gets set to expire after 2 minutes in the Temporary Internet Files folder but if I get rid of the 2 red lines in Login.aspx, how do I retrieve the username of the user in MyPage.aspx?


    Also is there any way by which MyPage.aspx can access the first parameter of the methods RedirectFromLoginPage & GetAuthCookie (which is txtUserName.Text)? If no, then what's the use of the first parameter in the methods RedirectFromLoginPage & GetAuthCookie?
    Thanks

    RON
    *********
    If you have an apple & I have an apple & we exchange our apples, then each of us will still have only 1 apple but if you have an idea & I have an idea & we exchange our ideas, then each of us will have 2 ideas
  • Re: Cookies?

    09-30-2006, 3:37 PM
    • All-Star
      17,710 point All-Star
    • vivek_iit
    • Member since 06-18-2006, 2:13 PM
    • New Delhi
    • Posts 3,171
    • TrustedFriends-MVPs

    Hello,

    You should not overwrite the cookie's Value as it stores the encrypted ticket information in it (which you have over written with the username value).

    Also, you do not need to use FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, True) when you are setting the cookie yourself. In your case, the cookie will not expire as the page has re-directed using the cookie set in the above method. Use like:

    HttpCookie cookie = FormsAuthentication.GetAuthCookie(Username, true); //true is used to create a persistent cookie

     

    cookie.Expires = DateTime.Now.AddSeconds(10); //this will expire after 3 months

    Response.Cookies.Add(cookie);

    Response.Redirect(FormsAuthentication.GetRedirectUrl(Username, true));//redirect to the originally requested page

    If you want to get the username, store it in session or create another cookie, but do not tamper with the values of the Authentication cookies.

     Hope this helps,

    Vivek

  • Re: Cookies?

    10-01-2006, 11:16 AM
    • Participant
      961 point Participant
    • RN5A
    • Member since 07-13-2006, 7:59 PM
    • Mumbai, India
    • Posts 406
    If the encrypted ticket information can't be used to retrieve the username, then what for is username passed as the first parameter to the GetAuthCookie, SetAuthCookieRedirectFromLoginPage methods of the FormsAuthentication object? How does an ASP.NET developer make use of the encrypted ticket information? Can't the encrypted ticket information be used to ensure that a user isn't forced to login again & again once the FormsAuthentication cookie gets created in the user's local m/c until the cookie is set to expire?

    Also why use Response.Redirect (which involves 2 round trips from the server to the client) when the RedirectFromLoginPage method can be used?
    Thanks

    RON
    *********
    If you have an apple & I have an apple & we exchange our apples, then each of us will still have only 1 apple but if you have an idea & I have an idea & we exchange our ideas, then each of us will have 2 ideas
  • Re: Cookies?

    10-03-2006, 8:59 AM
    • All-Star
      17,710 point All-Star
    • vivek_iit
    • Member since 06-18-2006, 2:13 PM
    • New Delhi
    • Posts 3,171
    • TrustedFriends-MVPs

    GethAuthCookie puts the user name in an object of FormsAuthenticationTicket and later calls the FormsAuthentication.Encrypt(ticket) method. You can access this value as:

    protected void Page_Load(object sender, EventArgs e)
    {
      
    HttpCookie loginCookie = Request.Cookies["Test"];  //"Test" is the cookie name specified in the config file.
      
    FormsAuthenticationTicket t = FormsAuthentication.Decrypt(loginCookie.Value);
      
    string userName = t.Name; //this is the userName stored while cookie was created as HttpCookie cookie = FormsAuthentication.GetAuthCookie(Username, true);
    }

    But use this code only when needed since many times using the Session is more helpful as cookies can be tampered at client side. In case you need persistent cookies, then this is ok. But it is recommended that you expire cookies as soon as possible (besides keeping Session timeouts as low as possible).

    Also, RedirectFormLoginPage uses Response.Redirect() only. It seems you did not read my blog carefully enough :-).

    Hope this helps,

    Vivek

  • Re: Cookies?

    10-06-2006, 11:23 AM
    • Participant
      961 point Participant
    • RN5A
    • Member since 07-13-2006, 7:59 PM
    • Mumbai, India
    • Posts 406
    That's EXACTLY what I wanted to know - how to use the encrypted FormsAuthenticationTicket to retrieve the username. Thanks a lot, Vivek, for all the help you have extended towards me.

    I am sorry....I guess I overlooked that Response.Redirect line in your blog....
    Thanks

    RON
    *********
    If you have an apple & I have an apple & we exchange our apples, then each of us will still have only 1 apple but if you have an idea & I have an idea & we exchange our ideas, then each of us will have 2 ideas
  • Re: Cookies?

    10-07-2006, 3:46 PM
    • Participant
      961 point Participant
    • RN5A
    • Member since 07-13-2006, 7:59 PM
    • Mumbai, India
    • Posts 406
    Vivek, there's one thing that I don't understand. When I am setting the second parameter of the GetAuthCookie to True, why isn't the cookie becoming persistent. For e.g. consider this code:

    Dim hCookie As HttpCookie
    hCookie = FormsAuthentication.GetAuthCookie(txtUserName.Text,
    True)
    hCookie.Expires = DateTime.Now.AddMonths(2)
    Response.Cookies.Add(hCookie)


    A cookie gets created today (8th October 2006) after I login. Next I am taken to another ASPX page named Enter.aspx which says Hello <username>. I have set this cookie to expire after 2 months i.e. the cookie should expire on 8th December 2006. When I view the cookie in the Temporary Internet Files folder & just click this cookie, the expiry date, as expected, is set to 8th December 2006.

    Note that if a user tries to navigate to Enter.aspx without logging in, he is directed to the login page which has the code snippet shown above.

    I close the browser window I used to login & open a new browser window. When I navigate to Enter.aspx, I am shown the Hello <username> message. Irrespective of the number of times I open a new browser window today & navigate to Enter.aspx, I am always shown the message Hello <username>. At no time have I logged out today. OK.....fine....no problem till here.

    But when I navigate to Enter.aspx tomorrow (i.e. 9th October 2006) & try to navigate to Enter.aspx, I am redirected to the login page to login. Why? Using the GetAuthCookie method of the FormsAuthentication object, I have created a persistent cookie by setting the second parameter of the GetAuthCookie to True. Even the cookie in the Temporary Internet Files folder says that it is set to expire on 8th December 2006.

    So why am I being told to login again when I try to navigate to Enter.aspx on 9th October 2006? Why isn't the cookie persisting till 8th December 2006?
    Thanks

    RON
    *********
    If you have an apple & I have an apple & we exchange our apples, then each of us will still have only 1 apple but if you have an idea & I have an idea & we exchange our ideas, then each of us will have 2 ideas
  • Re: Cookies?

    10-09-2006, 8:27 PM
    • Participant
      961 point Participant
    • RN5A
    • Member since 07-13-2006, 7:59 PM
    • Mumbai, India
    • Posts 406
    Vivek, you don't have the answer to my last post in this thread??
    Thanks

    RON
    *********
    If you have an apple & I have an apple & we exchange our apples, then each of us will still have only 1 apple but if you have an idea & I have an idea & we exchange our ideas, then each of us will have 2 ideas
  • Re: Cookies?

    10-10-2006, 7:47 AM
    • All-Star
      17,710 point All-Star
    • vivek_iit
    • Member since 06-18-2006, 2:13 PM
    • New Delhi
    • Posts 3,171
    • TrustedFriends-MVPs

    Hi,

    I got a bit busy but thanks to your post, I got something to learn myself. I think the MSDN documentation is wrong/confusing when it says that "Persistent cookies do not time out." (http://msdn2.microsoft.com/en-us/library/1d3t3c61.aspx)

    Persistent cookies take the value of the "timeout" attribute in the Web.Config file and to create real persistent cookies you need to make this value very big, like timeout="5000000".

    See this post for more info: http://weblogs.asp.net/scottgu/archive/2005/11/08/430011.aspx

    Hope this helps,

    Vivek

     

  • Re: Cookies?

    10-10-2006, 7:49 AM
    • All-Star
      17,710 point All-Star
    • vivek_iit
    • Member since 06-18-2006, 2:13 PM
    • New Delhi
    • Posts 3,171
    • TrustedFriends-MVPs
  • Re: Cookies?

    10-12-2006, 11:26 AM
    • Participant
      961 point Participant
    • RN5A
    • Member since 07-13-2006, 7:59 PM
    • Mumbai, India
    • Posts 406
    No problem, Vivek if you got busy. After all, everyone's busy in this world. Still there are nice people like you who take some time out of their busy schedule to help people like me.

    Now getting back to the main topic, I tried setting the timeout in the web.config file to 50000000 but still doesn't make any difference. The user is forced to login when he opens his browser the very next next day.

    This persistent cookie issue has been really bugging me no end. I guess MS has persistent cookies in theory only & not in practical.......
    Thanks

    RON
    *********
    If you have an apple & I have an apple & we exchange our apples, then each of us will still have only 1 apple but if you have an idea & I have an idea & we exchange our ideas, then each of us will have 2 ideas
  • Re: Cookies?

    10-13-2006, 2:19 AM
    • All-Star
      17,710 point All-Star
    • vivek_iit
    • Member since 06-18-2006, 2:13 PM
    • New Delhi
    • Posts 3,171
    • TrustedFriends-MVPs

    It is working at my end. Let me elaborate how I am testing the same.

    I have created 2 pages, Login and Default. In the Login Page, I have this coding:

    protected void Page_Load(object sender, EventArgs e)
    {
    string Username = "vivekT";
    if (TextBox1.Text == "a")
    {
    HttpCookie cookie = FormsAuthentication.GetAuthCookie(Username, true); //true is used to create a persistent cookie
    cookie.Expires = DateTime.Now.AddMonths(3); //DOESN'T WORK
    Response.Cookies.Add(cookie);
    Response.Redirect(
    FormsAuthentication.GetRedirectUrl(Username, true));//redirect to the originally requested page
    }
    }

    My Web.Config setting:

    <authentication mode="Forms">

    <forms name="Test" loginUrl="Login.aspx" path="/" timeout="500000">

    </forms >

    </authentication>

    <authorization>

    <deny users="?" />

    </authorization>

    Now even if I change the date on my machine to, let's say, two days ahead, even then I am able to log in (as my expiry value is 5,00,000 minutes, slightly less than a year). So I think it is working if we assume that the expiry value is taken from the config file and not from the explicit cookie expiry set by us.

    Let me know if this is not the case with you.

    Vivek

  • Re: Cookies?

    10-13-2006, 11:18 AM
    • Participant
      961 point Participant
    • RN5A
    • Member since 07-13-2006, 7:59 PM
    • Mumbai, India
    • Posts 406
    Yes, Vivek, you have hit the nail on the head. To ensure that the cookie becomes persistent, the timeout property of the <forms> tag needs to be set in the web.config file; the Expires property of the HttpCookie object shouldn't be assigned any value in the ASPX page otherwise the cookie won't remain persistent.

    Finally I managed to see light at the end of the tunnel....all THANKS to YOU...
    Thanks

    RON
    *********
    If you have an apple & I have an apple & we exchange our apples, then each of us will still have only 1 apple but if you have an idea & I have an idea & we exchange our ideas, then each of us will have 2 ideas
  • Re: Cookies?

    11-01-2006, 2:45 PM
    • All-Star
      17,710 point All-Star
    • vivek_iit
    • Member since 06-18-2006, 2:13 PM
    • New Delhi
    • Posts 3,171
    • TrustedFriends-MVPs

    Hi,

    Few updates: I was again digging this issue in another thread and got to know that there is a way to custom persist cookie in 2.0 by setting a custom FormsAuthenticationTicket expiry.

    Check this post:http://forums.asp.net/thread/1448345.aspx

    I have also updated my blog: http://geekswithblogs.net/vivek/archive/2006/10/13/93956.aspx

    Regards,

    Vivek

Page 1 of 2 (17 items) 1 2 Next >