疾风萧萧

See, this isn't the finish line.The future is the finish line......
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

用户点击Log In按钮后发生了什么?(续篇1)

Posted on 2006-06-09 08:58  疾风  阅读(894)  评论(0编辑  收藏  举报
    上篇我们说到在Login控件的AttemptLogin方法中,最终使用了FormAuthentication的SetAuthCookie(string userName, bool createPersistentCookie)
来设置Cookie,那具体是怎么工作的呢?让我们看看它的代码:

1 public static void SetAuthCookie(string userName, bool createPersistentCookie)
2 {
3       FormsAuthentication.Initialize();
4       FormsAuthentication.SetAuthCookie(userName, createPersistentCookie, FormsAuthentication.FormsCookiePath);
5 }

    嗯,首先调用Initialize()方法初始化一把,察看Initialize()的代码得知它的主要作用是设置一下FormAuthentication的基本参数,包括_FormsName、_RequireSSL、_FormsCookiePath、_TimeOut、_LoginUrl、DefaultUrl 等,最后把_Initialized内部状态设置成true(其中使用了线程同步锁)。

    然后使用由Initialize()方法中设置好的FormsAuthentication.FormsCookiePath属性来调用FormsAuthentication.SetAuthCookie(userName, createPersistentCookie, FormsAuthentication.FormsCookiePath)方法,让我们先看看MSDN怎么描述这个方法的功能:

    Creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, using the supplied cookie path or the URL.

    再来看看这个方法的代码:

 1 public static void SetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath)
 2 {
 3       
 4       HttpContext context1 = HttpContext.Current;
 5       if (!context1.Request.IsSecureConnection && FormsAuthentication.RequireSSL)
 6       {
 7             throw new HttpException(SR.GetString("Connection_not_secure_creating_secure_cookie"));
 8       }
 9       bool flag1 = CookielessHelperClass.UseCookieless(context1, false, FormsAuthentication.CookieMode);
10       HttpCookie cookie1 = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie, flag1 ? "/" : strCookiePath, !flag1);
11       if (!flag1)
12       {
13             HttpContext.Current.Response.Cookies.Add(cookie1);
14             context1.CookielessHelper.SetCookieValue('F'null);
15       }
16       else
17       {
18             context1.CookielessHelper.SetCookieValue('F', cookie1.Value);
19       }
20 }
21 

    其中CookielessHelperClass.UseCookieless(...)方法的功能是判断当前请求上下文是否接受本地Cookie(不接受的话返回true),如果请求上下文接受本地Cookie则直接把Cookie加到请求上下文中,如果请求上下文不接受本地Cookie则把Cookie的值放入名为“F”的Cookie值中,以待后用。
    读到这里,我们已经清楚地知道用户点击Log In按钮后发生了什么事、Asp.net 2.0是如何记录登录信息的了,但是如果想更清楚地知道这个Cookie是如何生成的,还得去读读 FormsAuthentication.GetAuthCookie (String, Boolean, String) 方法。