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

  • 相关阅读:
    Python 工匠:编写条件分支代码的技巧
    component-scan标签的use-default-filters属性的作用以及原理分析
    Serverless 架构的优点和缺点
    5 种使用 Python 代码轻松实现数据可视化的方法
    曾经我是一个只会excel的数据分析师,直到我遇到了……
    月薪45K的Python爬虫工程师告诉你爬虫应该怎么学,太详细了!
    用 Python 构建一个极小的区块链
    第六章 程序数据集散地;数据库
    MyBankgon功能
    第四章 深入C#的string类
  • 原文地址:https://www.cnblogs.com/yeagen/p/3427465.html
Copyright © 2011-2022 走看看