深入理解Forms 身份验证


本文将介绍.net中Form身份验证的必要元素如FormsAuthentication.SetAuthCookie,FormsAuthentication.Encrypt,FormsAuthentication.Decrypt,machineKey,Identity,Principal等和.net如何定义和实现他们。 

一.介绍一些我们的应用场景吧 

index.aspx要求登陆,如果没有登陆跳转到login.aspx页面,登录成功后跳转到index.aspx页面,并显示必要信息. 

二.实现: 

2.1 web.config:

  1. <system.web>      
  2.     <authentication mode="Forms">  
  3.         <forms name="adminlogin" loginUrl="login.aspx">  
  4.         </forms>  
  5.     </authentication>  
  6.     <authorization>  
  7.         <deny users="?"/>  
  8.     </authorization>  
  9. </system.web>  

注意:<authorization>          
<deny users="?"/>      
</authorization>  不是必须的。 

如果有的话,当我们访问index.aspx时,.net底层负责检测是否登录,如果没有登陆,.net根据我们的配置跳转的login.aspx页面。

如果没有的话,必须我们自己写必要的代码,来跳转。

2.2 login.aspx主要进行身份验证,.net中有下列实现:

2.1.1 FormsAuthentication.RedirectFromLoginPage

  1. if (username == "admin" &&  password == "1")  
  2. {                  
  3.     
    FormsAuthentication.RedirectFromLoginPage(username, true);                  
  4. }  

该作用是设置票据,自动跳转到来源页面(index.aspx).注意来源页面必须带一个ReturnUrl,否则会出错  

  1. if (!User.Identity.IsAuthenticated)  
  2. {  
  3.     Response.Redirect("/login.aspx?ReturnUrl=/index.aspx");  
  4. }  

2.2.2 FormsAuthentication.SetAuthCookie 

  1. if (username == "admin" &&  password == "1")  
  2. {  
  3.     FormsAuthentication.SetAuthCookie(username, true);  
  4.     Response.Redirect("index.aspx");  
  5. }  

该方法比第一种方法有更大的灵活性,可以自定义登陆成功后,返回的url. 

2.2.3 自定义票据cookie 

  1. if (username == "admin" &&  password == "1")  
  2. {  
  3.     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), false, "Manager");  
  4.     string cookieStr = FormsAuthentication.Encrypt(ticket);  
  5.     HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr);  
  6.     cookie.Expires = ticket.Expiration;  
  7.     cookie.Path = FormsAuthentication.FormsCookiePath;  
  8.     Response.Cookies.Add(cookie);  
  9.     Response.Redirect("index.aspx");                  
  10. }  

该方法比第二中方法又有更大的灵活性。 

2.3.1
FormsAuthentication.RedirectFromLoginPage的原理:

  1. public static void RedirectFromLoginPage(string userName, bool createPersistentCookie, string strCookiePath)  
  2.         {  
  3.             Initialize();  
  4.             if (userName != null)  
  5.             {  
  6.                 HttpContext current = HttpContext.Current;  
  7.                 string returnUrl = GetReturnUrl(true);  
  8.                 if (CookiesSupported || IsPathWithinAppRoot(current, returnUrl))  
  9.                 {  
  10.                     SetAuthCookie(userName, createPersistentCookie, strCookiePath);  
  11.                     returnUrl = RemoveQueryStringVariableFromUrl(returnUrl, FormsCookieName);  
  12.                     if (!CookiesSupported)  
  13.                     {  
  14.                         int index = returnUrl.IndexOf("://", StringComparison.Ordinal);  
  15.                         if (index > 0)  
  16.                         {  
  17.                             index = returnUrl.IndexOf('/', index + 3);  
  18.                             if (index > 0)  
  19.                             {  
  20.                                 returnUrl = returnUrl.Substring(index);  
  21.                             }  
  22.                         }  
  23.                     }  
  24.                 }  
  25.                 else  
  26.                 {  
  27.                     if (!EnableCrossAppRedirects)  
  28.                     {  
  29.                         throw new HttpException(System.Web.SR.GetString("Can_not_issue_cookie_or_redirect"));  
  30.                     }  
  31.                     HttpCookie cookie = GetAuthCookie(userName, createPersistentCookie, strCookiePath);  
  32.                     returnUrl = RemoveQueryStringVariableFromUrl(returnUrl, cookie.Name);  
  33.                     if (returnUrl.IndexOf('?') > 0)  
  34.                     {  
  35.                         string str2 = returnUrl;  
  36.                         returnUrl = str2 + "&" + cookie.Name + "=" + cookie.Value;  
  37.                     }  
  38.                     else  
  39.                     {  
  40.                         string str3 = returnUrl;  
  41.                         returnUrl = str3 + "?" + cookie.Name + "=" + cookie.Value;  
  42.                     }  
  43.                 }  
  44.                 current.Response.Redirect(returnUrl, false);  
  45.             }  
  46.         }  
  1. internal static string GetReturnUrl(bool useDefaultIfAbsent)  
  2. {  
  3.     Initialize();  
  4.     HttpContext current = HttpContext.Current;  
  5.     string str = current.Request.QueryString["ReturnUrl"];  
  6.     if (str == null)  
  7.     {  
  8.         str = current.Request.Form["ReturnUrl"];  
  9.         if ((!string.IsNullOrEmpty(str) && !str.Contains("/")) && str.Contains("%"))  
  10.         {  
  11.             str = HttpUtility.UrlDecode(str);  
  12.         }  
  13.     }  
  14.     if ((!string.IsNullOrEmpty(str) && !EnableCrossAppRedirects) && !UrlPath.IsPathOnSameServer(str, current.Request.Url))  
  15.     {  
  16.         str = null;  
  17.     }  
  18.     if (!string.IsNullOrEmpty(str) && CrossSiteScriptingValidation.IsDangerousUrl(str))  
  19.     {  
  20.         throw new HttpException(System.Web.SR.GetString("Invalid_redirect_return_url"));  
  21.     }  
  22.     if ((str == null) && useDefaultIfAbsent)  
  23.     {  
  24.         return DefaultUrl;  
  25.     }  
  26.     return str;  
  27. }  

本质上:FormsAuthentication.RedirectFromLoginPage是调用了FormsAuthentication.SetAuthCookie,然后Response.Redirect(current.Request.QueryString["ReturnUrl"],
false) 

2.3.2 FormsAuthentication.SetAuthCookie原理:

 

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

 

  1. private static HttpCookie GetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath, bool hexEncodedTicket)  
  2. {  
  3.     Initialize();  
  4.     if (userName == null)  
  5.     {  
  6.         userName = string.Empty;  
  7.     }  
  8.     if ((strCookiePath == null) || (strCookiePath.Length < 1))  
  9.     {  
  10.         strCookiePath = FormsCookiePath;  
  11.     }  
  12.     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, userName, DateTime.Now, DateTime.Now.AddMinutes((double) _Timeout), createPersistentCookie, string.Empty, strCookiePath);  
  13.     string str = Encrypt(ticket, hexEncodedTicket);  
  14.     if ((str == null) || (str.Length < 1))  
  15.     {  
  16.         throw new HttpException(System.Web.SR.GetString("Unable_to_encrypt_cookie_ticket"));  
  17.     }  
  18.     HttpCookie cookie = new HttpCookie(FormsCookieName, str);  
  19.     cookie.HttpOnly = true;  
  20.     cookie.Path = strCookiePath;  
  21.     cookie.Secure = _RequireSSL;  
  22.     if (_CookieDomain != null)  
  23.     {  
  24.         cookie.Domain = _CookieDomain;  
  25.     }  
  26.     if (ticket.IsPersistent)  
  27.     {  
  28.         cookie.Expires = ticket.Expiration;  
  29.     }  
  30.     return cookie;  
  31. }  

FormsAuthentication.SetAuthCookie本质上调用了FormsAuthentication.GetAuthCookie,而FormsAuthentication.GetAuthCookie得代码和我们上面跳到的第三种方法何其相似呀。

注意了:第二种方法和第三种方法还是有区别的。

a.第三种方法可以设置更多的信息如:

第二种:附加信息为string.Empty

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, userName,
DateTime.Now, DateTime.Now.AddMinutes((double) _Timeout),
createPersistentCookie, string.Empty,
strCookiePath);
第二种:附加信息为"Manager"
FormsAuthenticationTicket ticket = new
FormsAuthenticationTicket(1, username, DateTime.Now,
DateTime.Now.AddMinutes(30), false, "Manager"); 

b.第三种方法可以更灵活的设置domain等信息。

第二种使用的是默认的,如果在web.config配置了domain,就使用config中的 

  1. <authentication mode="Forms">  
  2.     <forms name="adminlogin" loginUrl="loginRedirect.aspx" domain ="bbs.it118.org">  
  3.     </forms>  
  4. </authentication>  

否则使用当前url的domain. 

但还是有个问题如果我在web.comfig
domain为bbs.it118.org的情况下,想设置domain为it118.org.第二种就必须如下写了: 

  1. FormsAuthentication.SetAuthCookie(user.UserNumb, isSave == true);  
  2. string cookieName = FormsAuthentication.FormsCookieName;  
  3. HttpCookie cookie = HttpContext.Current.Response.Cookies[cookieName];  
  4. if (cookie != null)  
  5. {  
  6.      cookie.Domain = "it118.org";  
  7. }  

2.3.3我们在分析第三种方法的原理

//生成票据,带有附加信息

 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username, DateTime.Now, DateTime.Now.AddMinutes(30), false, "Manager");

//加密票据
string cookieStr = FormsAuthentication.Encrypt(ticket);

//生成一个cookie,

//cookiename来自web.config配置的name 

  1. <authentication mode="Forms">  
  2.     <forms name="adminlogin" loginUrl="loginRedirect.aspx" domain ="bbs.it118.org">  
  3.     </forms>  
  4. </authentication>  

//cookie的值来自加密的票据
HttpCookie cookie = new
HttpCookie(FormsAuthentication.FormsCookieName, cookieStr); 

//设置cookie的过期时间和路径等
               
cookie.Expires =
ticket.Expiration;
               
cookie.Path =
FormsAuthentication.FormsCookiePath;
               
Response.Cookies.Add(cookie);
               
Response.Redirect("index.aspx"); 

这里重点提一下加密算法 

  1. private static string Encrypt(FormsAuthenticationTicket ticket, bool hexEncodedTicket)  
  2.         {  
  3.             if (ticket == null)  
  4.             {  
  5.                 throw new ArgumentNullException("ticket");  
  6.             }  
  7.             Initialize();  
  8.             byte[] buf = MakeTicketIntoBinaryBlob(ticket);  
  9.             if (buf == null)  
  10.             {  
  11.                 return null;  
  12.             }  
  13.             if ((_Protection == FormsProtectionEnum.All) || (_Protection == FormsProtectionEnum.Validation))  
  14.             {  
  15.                 byte[] src = MachineKeySection.HashData(buf, null, 0, buf.Length);  
  16.                 if (src == null)  
  17.                 {  
  18.                     return null;  
  19.                 }  
  20.                 byte[] dst = new byte[src.Length + buf.Length];  
  21.                 Buffer.BlockCopy(buf, 0, dst, 0, buf.Length);  
  22.                 Buffer.BlockCopy(src, 0, dst, buf.Length, src.Length);  
  23.                 buf = dst;  
  24.             }  
  25.             if ((_Protection == FormsProtectionEnum.All) || (_Protection == FormsProtectionEnum.Encryption))  
  26.             {  
  27.                 buf = MachineKeySection.EncryptOrDecryptData(true, buf, null, 0, buf.Length, IVType.Random);  
  28.             }  
  29.             if (!hexEncodedTicket)  
  30.             {  
  31.                 return HttpServerUtility.UrlTokenEncode(buf);  
  32.             }  
  33.             return MachineKeySection.ByteArrayToHexString(buf, 0);  
  34.         }  

加密利用非对称加密技术,其中的machinekey来自于web.config。  

  1. <machineKey validationKey="1E7A0332AD3930B95A82A1BFF82B041791366BD14DE8390B0B7EF3E7B05" decryptionKey="702BD19727054E63574" validation="SHA1"/>  

3.index.aspx  

  1. if (!User.Identity.IsAuthenticated)  
  2. {  
  3.     Response.Redirect("/login.aspx?ReturnUrl=/index.aspx");  
  4. }  
  5.   
  6. Response.Write("用户名:" + User.Identity.Name  );  

当登陆成功后User.Identity.IsAuthenticated为true,User.Identity.Name为上述三种方法设置的username。

上面的这一切信息是“自动的”,至少我们不用编写人任何代码即可得到。太神奇了。记住:没有自动的东西。要么自己写要么是别的帮我们处理的。微软一向助开发人员为快乐之本,一定是他干的。

 

  1.       
    private void OnAuthenticate(FormsAuthenticationEventArgs e)  
  2.        {  
  3.            HttpCookie cookie = null;  
  4.            if (this._eventHandler != null)  
  5.            {  
  6.                this._eventHandler(this, e);  
  7.            }  
  8.            if (e.Context.User == null)  
  9.            {  
  10.                if (e.User != null)  
  11.                {  
  12.                    e.Context.SetPrincipalNoDemand(e.User);  
  13.                }  
  14.                else  
  15.                {  
  16.                    FormsAuthenticationTicket tOld = null;  
  17.                    bool cookielessTicket = false;  
  18.                    try  
  19.                    {  
  20.                        tOld = ExtractTicketFromCookie(e.Context, FormsAuthentication.FormsCookieName, out cookielessTicket);  
  21.                    }  
  22.                    catch  
  23.                    {  
  24.                        tOld = null;  
  25.                    }  
  26.                    if ((tOld != null) && !tOld.Expired)  
  27.                    {  
  28.                        FormsAuthenticationTicket ticket = tOld;  
  29.                        if (FormsAuthentication.SlidingExpiration)  
  30.                        {  
  31.                            ticket = FormsAuthentication.RenewTicketIfOld(tOld);  
  32.                        }  
  33.                        e.Context.SetPrincipalNoDemand(new GenericPrincipal(new FormsIdentity(ticket), new string[0]));  
  34.                        if (!cookielessTicket && !ticket.CookiePath.Equals("/"))  
  35.                        {  
  36.                            cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName];  
  37.                            if (cookie != null)  
  38.                            {  
  39.                                cookie.Path = ticket.CookiePath;  
  40.                            }  
  41.                        }  
  42.                        if (ticket != tOld)  
  43.                        {  
  44.                            if ((cookielessTicket && (ticket.CookiePath != "/")) && (ticket.CookiePath.Length > 1))  
  45.                            {  
  46.                                ticket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, ticket.UserData, "/");  
  47.                            }  
  48.                            string cookieValue = FormsAuthentication.Encrypt(ticket);  
  49.                            if (cookielessTicket)  
  50.                            {  
  51.                                e.Context.CookielessHelper.SetCookieValue('F', cookieValue);  
  52.                                e.Context.Response.Redirect(e.Context.Request.PathWithQueryString);  
  53.                            }  
  54.                            else  
  55.                            {  
  56.                                if (cookie != null)  
  57.                                {  
  58.                                    cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName];  
  59.                                }  
  60.                                if (cookie == null)  
  61.                                {  
  62.                                    cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue);  
  63.                                    cookie.Path = ticket.CookiePath;  
  64.                                }  
  65.                                if (ticket.IsPersistent)  
  66.                                {  
  67.                                    cookie.Expires = ticket.Expiration;  
  68.                                }  
  69.                                cookie.Value = cookieValue;  
  70.                                cookie.Secure = FormsAuthentication.RequireSSL;  
  71.                                cookie.HttpOnly = true;  
  72.                                if (FormsAuthentication.CookieDomain != null)  
  73.                                {  
  74.                                    cookie.Domain = FormsAuthentication.CookieDomain;  
  75.                                }  
  76.                                e.Context.Response.Cookies.Remove(cookie.Name);  
  77.                                e.Context.Response.Cookies.Add(cookie);  
  78.                            }  
  79.                        }  
  80.                    }  
  81.               
    }  
  82.            }  
  83.        }  

 

  1. private static FormsAuthenticationTicket ExtractTicketFromCookie(HttpContext context, string name, out bool cookielessTicket)  
  2.        {  
  3.            FormsAuthenticationTicket ticket = null;  
  4.            string encryptedTicket = null;  
  5.            FormsAuthenticationTicket ticket2;  
  6.            bool flag = false;  
  7.            bool flag2 = false;  
  8.            try  
  9.            {  
  10.                try  
  11.                {  
  12.                    cookielessTicket = CookielessHelperClass.UseCookieless(context, false, FormsAuthentication.CookieMode);  
  13.                    if (cookielessTicket)  
  14.                    {  
  15.                        encryptedTicket = context.CookielessHelper.GetCookieValue('F');  
  16.                    }  
  17.                    else  
  18.                    {  
  19.                        HttpCookie cookie = context.Request.Cookies[name];  
  20.                        if (cookie != null)  
  21.                        {  
  22.                            encryptedTicket = cookie.Value;  
  23.                        }  
  24.                    }  
  25.                    if ((encryptedTicket != null) && (encryptedTicket.Length > 1))  
  26.                    {  
  27.                        try  
  28.                        {  
  29.                            ticket = FormsAuthentication.Decrypt(encryptedTicket);  
  30.                        }  
  31.                        catch  
  32.                        {  
  33.                            if (cookielessTicket)  
  34.                            {  
  35.                                context.CookielessHelper.SetCookieValue('F', null);  
  36.                            }  
  37.                            else  
  38.                            {  
  39.                                context.Request.Cookies.Remove(name);  
  40.                            }  
  41.                            flag2 = true;  
  42.                        }  
  43.                        if (ticket == null)  
  44.                        {  
  45.                            flag2 = true;  
  46.                        }  
  47.                        if (((ticket != null) && !ticket.Expired) && ((cookielessTicket || !FormsAuthentication.RequireSSL) || context.Request.IsSecureConnection))  
  48.                        {  
  49.                            return ticket;  
  50.                        }  
  51.                        if ((ticket != null) && ticket.Expired)  
  52.                        {  
  53.                            flag = true;  
  54.                        }  
  55.                        ticket = null;  
  56.                        if (cookielessTicket)  
  57.                        {  
  58.                            context.CookielessHelper.SetCookieValue('F', null);  
  59.                        }  
  60.                        else  
  61.                        {  
  62.                            context.Request.Cookies.Remove(name);  
  63.                        }  
  64.                    }  
  65.                    if (FormsAuthentication.EnableCrossAppRedirects)  
  66.                    {  
  67.                        encryptedTicket = context.Request.QueryString[name];  
  68.                        if ((encryptedTicket != null) && (encryptedTicket.Length > 1))  
  69.                        {  
  70.                            if (!cookielessTicket && (FormsAuthentication.CookieMode == HttpCookieMode.AutoDetect))  
  71.                            {  
  72.                                cookielessTicket = CookielessHelperClass.UseCookieless(context, true, FormsAuthentication.CookieMode);  
  73.                            }  
  74.                            try  
  75.                            {  
  76.                                ticket = FormsAuthentication.Decrypt(encryptedTicket);  
  77.                            }  
  78.                            catch  
  79.                            {  
  80.                                flag2 = true;  
  81.                            }  
  82.                            if (ticket == null)  
  83.                            {  
  84.                                flag2 = true;  
  85.                            }  
  86.                        }  
  87.                        if ((ticket == null) || ticket.Expired)  
  88.                        {  
  89.                            encryptedTicket = context.Request.Form[name];  
  90.                            if ((encryptedTicket != null) && (encryptedTicket.Length > 1))  
  91.                            {  
  92.                                if (!cookielessTicket && (FormsAuthentication.CookieMode == HttpCookieMode.AutoDetect))  
  93.                                {  
  94.                                    cookielessTicket = CookielessHelperClass.UseCookieless(context, true, FormsAuthentication.CookieMode);  
  95.                                }  
  96.                                try  
  97.                                {  
  98.                                    ticket = FormsAuthentication.Decrypt(encryptedTicket);  
  99.                                }  
  100.                                catch  
  101.                                {  
  102.                                    flag2 = true;  
  103.                                }  
  104.                                if (ticket == null)  
  105.                                {  
  106.                                    flag2 = true;  
  107.                                }  
  108.                            }  
  109.                        }  
  110.                    }  
  111.                    if ((ticket == null) || ticket.Expired)  
  112.                    {  
  113.                        if ((ticket != null) && ticket.Expired)  
  114.                        {  
  115.                            flag = true;  
  116.                        }  
  117.                        return null;  
  118.                    }  
  119.                    if (FormsAuthentication.RequireSSL && !context.Request.IsSecureConnection)  
  120.                    {  
  121.                        throw new HttpException(System.Web.SR.GetString("Connection_not_secure_creating_secure_cookie"));  
  122.                    }  
  123.                    if (cookielessTicket)  
  124.                    {  
  125.                        if (ticket.CookiePath != "/")  
  126.                        {  
  127.                            ticket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, ticket.UserData, "/");  
  128.                            encryptedTicket = FormsAuthentication.Encrypt(ticket);  
  129.                        }  
  130.                        context.CookielessHelper.SetCookieValue('F', encryptedTicket);  
  131.                        string url = FormsAuthentication.RemoveQueryStringVariableFromUrl(context.Request.PathWithQueryString, name);  
  132.                        context.Response.Redirect(url);  
  133.                    }  
  134.                    else  
  135.                    {  
  136.                        HttpCookie cookie2 = new HttpCookie(name, encryptedTicket);  
  137.                        cookie2.HttpOnly = true;  
  138.                        cookie2.Path = ticket.CookiePath;  
  139.                        if (ticket.IsPersistent)  
  140.                        {  
  141.                            cookie2.Expires = ticket.Expiration;  
  142.                        }  
  143.                        cookie2.Secure = FormsAuthentication.RequireSSL;  
  144.                        if (FormsAuthentication.CookieDomain != null)  
  145.                        {  
  146.                            cookie2.Domain = FormsAuthentication.CookieDomain;  
  147.                        }  
  148.                        context.Response.Cookies.Remove(cookie2.Name);  
  149.                        context.Response.Cookies.Add(cookie2);  
  150.                    }  
  151.                    ticket2 = ticket;  
  152.                }  
  153.                finally  
  154.                {  
  155.                    if (flag2)  
  156.                    {  
  157.                        WebBaseEvent.RaiseSystemEvent(null, 0xfa5, 0xc419);  
  158.                    }  
  159.                    else if (flag)  
  160.                    {  
  161.                        WebBaseEvent.RaiseSystemEvent(null, 0xfa5, 0xc41a);  
  162.                    }  
  163.                }  
  164.            }  
  165.            catch  
  166.            {  
  167.                throw;  
  168.            }  
  169.            return ticket2;  
  170.        }  
  1.       
    internal void SetPrincipalNoDemand(IPrincipal principal, bool needToSetNativePrincipal)  
  2.        {  
  3.            this._user = principal;  
  4.            if ((needToSetNativePrincipal && this._isIntegratedPipeline) && (this._notificationContext.CurrentNotification == RequestNotification.AuthenticateRequest))  
  5.            {  
  6.                IntPtr zero = IntPtr.Zero;  
  7.                try  
  8.                {  
  9.                    IIS7WorkerRequest request = this._wr as IIS7WorkerRequest;  
  10.                    if (principal != null)  
  11.                    {  
  12.                        GCHandle handle = GCHandle.Alloc(principal);  
  13.                        try  
  14.                        {  
  15.                            zero = GCHandle.ToIntPtr(handle);  
  16.                            request.SetPrincipal(principal, zero);  
  17.                            return;  
  18.                        }  
  19.                        catch  
  20.                        {  
  21.                            zero = IntPtr.Zero;  
  22.                            if (handle.IsAllocated)  
  23.                            {  
  24.                                handle.Free();  
  25.                            }  
  26.                            throw;  
  27.                        }  
  28.                    }  
  29.                    request.SetPrincipal(null, IntPtr.Zero);  
  30.                }  
  31.                finally  
  32.                {  
  33.                    if (this._pManagedPrincipal != IntPtr.Zero)  
  34.                    {  
  35.                        GCHandle handle2 = GCHandle.FromIntPtr(this._pManagedPrincipal);  
  36.                        if (handle2.IsAllocated)  
  37.                        {  
  38.                            handle2.Free();  
  39.                        }  
  40.                    }  
  41.                    this._pManagedPrincipal = zero;  
  42.                }  
  43.            }  
  44.        }  

这段代码逻辑挺简单的: 

1.得到保存认证信息的cookie

2.解密

3.生成Principa Identity信息

4.赋值给context.user

这样我们访问User.Identity.IsAuthenticated
User.Identity.Name就自动有值了。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM