• 基于forms验证的目录角色权限的实现


    一个系统中经常有多种身份的用户,往往要根据其身份来控制目录的访问权限。asp.net提供了forms验证,能够轻易的在配置文件中设置用户对目录的访问权限,但是我在使用过程中,发现针对角色的控制并不是那么容易,通过在网上查找资料,终于解决这个问题。下面将主要的注意事项列出来。
    1、配置文件中,角色的allow项要放在deny项的前面,users要配置为*,而不是?

    代码
      <location path="Doctors">
        
    <system.web>   
          
    <authorization> 
            
    <allow roles="doctors"/>    //这个在前 
            
    <deny  users="*"/>       
          
    </authorization>
        
    </system.web>
      
    </location>


    2、将角色写入票据

    代码
    string role="doctors";
    FormsAuthenticationTicket Ticket 
    = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), false, role, "/");//建立身份验证票对象
            string HashTicket = FormsAuthentication.Encrypt(Ticket);//加密序列化验证票为字符串
            HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
            
    //生成Cookie
            Response.Cookies.Add(UserCookie);//输出Cookie
            Response.Redirect("");//重定向到用户申请的初始页面


    3、身份票据并没有直接提供对role的直接支持,需要在Application_AuthenticateRequest中对role进行解析

    代码
    string[] roles = authTicket.UserData.Split(new char[] { '|' });     
            FormsIdentity id 
    = new FormsIdentity(authTicket);
            System.Security.Principal.GenericPrincipal principal 
    = new System.Security.Principal.GenericPrincipal(id, roles);     
            Context.User 
    = principal;


    大致弄清这三点,就可以了。

    示例下载

  • 相关阅读:
    Run command in YMAL build pipeline or Release Pipeline
    Create Pipeline for Azure Apps
    Deploy Azure App Service with VS Code
    多线程总结笔记
    @Param注解
    Mac Idea2018.1破解
    空指针异常Caused by: java.lang.NullPointerException: null
    java集合面试题
    在IntelliJ IDEA中使用git
    分支管理
  • 原文地址:https://www.cnblogs.com/benz/p/role.html
Copyright © 2020-2023  润新知