zoukankan      html  css  js  c++  java
  • FormsAuthenticationTicket学习笔记

    自己的代码,很乱给自己看 

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "username", DateTime.Now, DateTime.Now.AddDays(365),
                 true, string.Format("{0}:{1}", "username", "password"), FormsAuthentication.FormsCookiePath);
                //这边的 string.Format("{0}:{1}", "username", "password"),也可以改为任何值,如密码或IP
                string ticString = FormsAuthentication.Encrypt(ticket);
                //将加密后的票据保存为cookie 
                HttpCookie coo = new HttpCookie(FormsAuthentication.FormsCookieName, ticString);
                //这里的IsPersistent不会自己判断,需要手工判断,但FormsAuthenticationTicket的expiration的值是有过期性的,无论cookie的Expires设置多久,只要expiration到期,即使cookie存在用户验证也将失败
                if (ticket.IsPersistent)
                {
                    coo.Expires = ticket.Expiration;
                }
                //使用加入了userdata的新cookie 
                Response.Cookies.Add(coo);
                //FormsAuthentication.SetAuthCookie("username", true);//这种是快速写法,用了这种写法就可以不用自己建ticket票据,也无法使用UserData等参数了
    
    
                //FormsAuthentication.SignOut//用来清除这个Cookie标记//FormsAuthentication.RedirectFromLoginPage(userID, createPersistentCookie);
    
            //    <authentication mode="Forms">
            //    <forms name=".MyCookie" loginUrl="Login.aspx" protection="All" timeout="60"/>
            //    </authentication> 

    总结:

    1.FormsAuthentication一共有两种生成并记录票具的方法:

      一种是自己new FormsAuthenticationTicket,然后自己保存到Cookie中,ticket的IsPersistent属性仅起到标识的作用,并不会去修改Cookies的到期时间,需要人工自己判断后设置cookies的到期时间(if (ticket.IsPersistent){coo.Expires = ticket.Expiration; })。

      另一种是使用FormsAuthentication.SetAuthCookie("username",IsPersistent: false);来快捷生成ticket,这种方法系统会自动新建一个cookies来保存ticket,并根据IsPersistent是否为true,以及webconfig中的timeout来确定cookies的到期时间。

    2.如果使用第一种方法,无论自己把cookies的时间设置为多久,只要ticket.Expiration到期了,及时cookies还存在,用户验证依然会失败。

    3.UserData是个好东西,可以用来存储IP地址,用于判断访问者是否是恶意截取cookies。

    推荐一篇好文:http://www.cnblogs.com/zxjyuan/archive/2009/08/21/1551196.html

  • 相关阅读:
    Node初学者入门,一本全面的NodeJS教程(转载)
    关于绑定变量的一点心得(转)
    【转】C++11 标准新特性: 右值引用与转移语义
    SVN分支与合并【超详细的图文教程】(转载)
    天猫魔盒屏蔽升级
    大页内存(HugePages)
    反向路径过滤——reverse path filter
    所做更改会影响共用模板Normal.dotm。是否保存此更改
    基于glew,freeglut的imshow
    glfw之hello world
  • 原文地址:https://www.cnblogs.com/yeagen/p/3427465.html
Copyright © 2011-2022 走看看