zoukankan      html  css  js  c++  java
  • FormsAuthenticationTicket基于forms的验证

    构建基于forms的验证机制过程如下:
     1,设置IIS为可匿名访问和asp.net web.config中设置为form验证
     2,检索数据存储验证用户,并检索角色(如果不是基于角色可不用)
     3,使用FormsAuthenticationTicket创建一个Cookie并回发到客户端,并存储
      角色到票据中,如:
      FormsAuthentication.SetAuthCookie(Username,true | false)
      cookies保存时间:
      HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName].Expires=DateTime.Now.AddDays(1)
     
      如果需要存储角色,采用:
     FormsAuthenticationTicket authTicket = new
     FormsAuthenticationTicket(
      1, // 版本号。
      txtUserName.Text, // 与身份验证票关联的用户名。
      DateTime.Now, // Cookie 的发出时间。
      DateTime.Now.AddMinutes(20),// Cookie 的到期日期。
      false, // 如果 Cookie 是持久的,为 true;否则为 false。
      roles ); // 将存储在 Cookie 中的用户定义数据。
      roles是一个角色字符串数组
      string encryptedTicket = FormsAuthentication.Encrypt(authTicket); //加密
     
      存入Cookie
      HttpCookie authCookie =
      new HttpCookie(FormsAuthentication.FormsCookieName,
      encryptedTicket);
     
      Response.Cookies.Add(authCookie);
     
     4,在Application_AuthenticateRequest事件中处理程序中(Global.asax)中,使用
      票创建IPrincipal对象并存在HttpContext.User中
      代码:
      HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
      FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);//解密
      string[] roles = authTicket.UserData.Split(new char[]{';'});//根据存入时的格式分解,;或|....
      Context.User = new GenericPrincipal(Context.User.Identity, Roles);//存到HttpContext.User中
     
     判断某个角色验证
     HttpContext.Current.User.IsInRole(roles)
     具体实现
     
     Web.config文件
     加入节点,name为COOKIE名称,loginUrl为没有通过验证跳转的地址
     <system.web>
      <authentication mode="Forms">
      <forms name="Hstear"
     loginUrl="login.aspx" protection="All" path="/" timeout="40"/>
      </authentication>
     </system.web>
     设置目录访问 path为目录名,roles为票据中的角色名
     发现网上的都说要单独一个WEB.CONFIG文件放在目录中,但实际在根目录中设置即可,单个文件也一样
     <location path="Admin">
      <system.web>
      <authorization>
      <allow roles="admin"/>
      <deny users="*"/>
      </authorization>
      </system.web>
     </location>
     Global.asax文件
     Application_AuthenticateRequest事件中加入
     
     原理,将用户角色信息保存在票据中,通过Global.asax,WEB.CONFIG中的设置,判断角色的权限
  • 相关阅读:
    t
    bert4keras
    embeding应用-airbnb推荐
    The Neural Autoregressive Distribution Estimator
    3.redis desktop manager--redis 可视化工具安装及使用
    Day06作业(postman接口测试)
    DRF学习day01(web应用模式,api接口,RESTful API规范,序列化,Django Rest_Framework)
    restFul接口设计规范
    Vue学习之荏苒资讯项目(一)
    微信小程序开发四:Promise的使用,解决回调地狱
  • 原文地址:https://www.cnblogs.com/mybluesky99/p/2080493.html
Copyright © 2011-2022 走看看