• SpringMVC整合Shiro与filterChainDefinitions过滤器配置


    SpringMVC整合Shiro,Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能。

    第一步:配置web.xml

      
      
      
      
      
        shiroFilter  
        org.springframework.web.filter.DelegatingFilterProxy  
          
          
        targetFilterLifecycle  
        true  
          
      
      
            shiroFilter  
            /*  
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    第二步:配置applicationContext.xml

      
      
    
      
      
      
      
          
      
    
      
      
      
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
              
                 /mydemo/login=anon  
                 /mydemo/getVerifyCodeImage=anon  
                 /main**=authc  
                 /user/info**=authc  
                 /admin/listUser**=authc,perms[admin:manage]  
              
        
      
    
      
      
    
      
      
      
      
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    第三步:自定义的Realm

    public class MyRealm extends AuthorizingRealm {  
        /** 
         * 为当前登录的Subject授予角色和权限 
         * @see  经测试:本例中该方法的调用时机为需授权资源被访问时 
         * @see  经测试:并且每次访问需授权资源时都会执行该方法中的逻辑,这表明本例中默认并未启用AuthorizationCache 
         * @see  个人感觉若使用了Spring3.1开始提供的ConcurrentMapCache支持,则可灵活决定是否启用AuthorizationCache 
         * @see  比如说这里从数据库获取权限信息时,先去访问Spring3.1提供的缓存,而不使用Shior提供的AuthorizationCache 
         */  
        @Override  
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){  
            //获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()  
            String currentUsername = (String)super.getAvailablePrincipal(principals);  
    //      List roleList = new ArrayList();  
    //      List permissionList = new ArrayList();  
    //      //从数据库中获取当前登录用户的详细信息  
    //      User user = userService.getByUsername(currentUsername);  
    //      if(null != user){  
    //          //实体类User中包含有用户角色的实体类信息  
    //          if(null!=user.getRoles() && user.getRoles().size()>0){  
    //              //获取当前登录用户的角色  
    //              for(Role role : user.getRoles()){  
    //                  roleList.add(role.getName());  
    //                  //实体类Role中包含有角色权限的实体类信息  
    //                  if(null!=role.getPermissions() && role.getPermissions().size()>0){  
    //                      //获取权限  
    //                      for(Permission pmss : role.getPermissions()){  
    //                          if(!StringUtils.isEmpty(pmss.getPermission())){  
    //                              permissionList.add(pmss.getPermission());  
    //                          }  
    //                      }  
    //                  }  
    //              }  
    //          }  
    //      }else{  
    //          throw new AuthorizationException();  
    //      }  
    //      //为当前用户设置角色和权限  
    //      SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();  
    //      simpleAuthorInfo.addRoles(roleList);  
    //      simpleAuthorInfo.addStringPermissions(permissionList);  
            SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();  
            //实际中可能会像上面注释的那样从数据库取得  
            if(null!=currentUsername && "mike".equals(currentUsername)){  
                //添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色    
                simpleAuthorInfo.addRole("admin");  
                //添加权限  
                simpleAuthorInfo.addStringPermission("admin:manage");  
                System.out.println("已为用户[mike]赋予了[admin]角色和[admin:manage]权限");  
                return simpleAuthorInfo;  
            }
            //若该方法什么都不做直接返回null的话,就会导致任何用户访问/admin/listUser.jsp时都会自动跳转到unauthorizedUrl指定的地址  
            //详见applicationContext.xml中的的配置  
            return null;  
        }  
    
    
        /** 
         * 验证当前登录的Subject 
         * @see  经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时 
         */  
        @Override  
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {  
            //获取基于用户名和密码的令牌  
            //实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的  
            //两个token的引用都是一样的
            UsernamePasswordToken token = (UsernamePasswordToken)authcToken;  
            System.out.println("验证当前Subject时获取到token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));  
    //      User user = userService.getByUsername(token.getUsername());  
    //      if(null != user){  
    //          AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), user.getNickname());  
    //          this.setSession("currentUser", user);  
    //          return authcInfo;  
    //      }else{  
    //          return null;  
    //      }  
            //此处无需比对,比对的逻辑Shiro会做,我们只需返回一个和令牌相关的正确的验证信息  
            //说白了就是第一个参数填登录用户名,第二个参数填合法的登录密码(可以是从数据库中取到的,本例中为了演示就硬编码了)  
            //这样一来,在随后的登录页面上就只有这里指定的用户和密码才能通过验证  
            if("mike".equals(token.getUsername())){  
                AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("mike", "mike", this.getName());  
                this.setSession("currentUser", "mike");  
                return authcInfo;  
            }
            //没有返回登录用户名对应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常  
            return null;  
        }  
    
    
        /** 
         * 将一些数据放到ShiroSession中,以便于其它地方使用 
         * @see  比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 
         */  
        private void setSession(Object key, Object value){  
            Subject currentUser = SecurityUtils.getSubject();  
            if(null != currentUser){  
                Session session = currentUser.getSession();  
                System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");  
                if(null != session){  
                    session.setAttribute(key, value);  
                }  
            }  
        }  
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103

    Shiro 权限管理filterChainDefinitions过滤器配置
    前言:shiro三大核心模块:Subject(用户)、SecurityManager(框架心脏)、Realm(Shiro与应用安全数据间的“桥梁”)
    SecurityManager去管理cacheManager缓存和sessionManager会话,sessionManager再去管理sessionDAO会话DAO 和sessionIdCookie会话ID生成器和sessionValidationScheduler会话验证调度器,cacheManager通过使用Ehcache实现,Realm通过自己自定义或者其他方式的权限存储来实现,比如登录等.
    使用统一数据访问层,通过编写实体类,编写Repository接口,最后通过配置文件实现
    Repository是标识,spring自动扫描,CrudRepository继承Repository实现curd,PagingAndSortingRepository继承CrudRepository实现分页排序,JpaRepository继承PagingAndSortingRepository实现JPA规范相关的方法,JpaSpecificationExecutor不属于Repository,比较特殊,它去实现一组JPA Criteria查询相关的方法

    /**
    * Shiro-1.2.2内置的FilterChain
    * @see =========================================================================================================
    * @see 1)Shiro验证URL时,URL匹配成功便不再继续匹配查找(所以要注意配置文件中的URL顺序,尤其在使用通配符时)
    * @see 故filterChainDefinitions的配置顺序为自上而下,以最上面的为准
    * @see 2)当运行一个Web应用程序时,Shiro将会创建一些有用的默认Filter实例,并自动地在[main]项中将它们置为可用
    * @see 自动地可用的默认的Filter实例是被DefaultFilter枚举类定义的,枚举的名称字段就是可供配置的名称
    * @see anon—————org.apache.shiro.web.filter.authc.AnonymousFilter
    * @see authc————–org.apache.shiro.web.filter.authc.FormAuthenticationFilter
    * @see authcBasic———org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
    * @see logout————-org.apache.shiro.web.filter.authc.LogoutFilter
    * @see noSessionCreation–org.apache.shiro.web.filter.session.NoSessionCreationFilter
    * @see perms————–org.apache.shiro.web.filter.authz.PermissionAuthorizationFilter
    * @see port—————org.apache.shiro.web.filter.authz.PortFilter
    * @see rest—————org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
    * @see roles————–org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
    * @see ssl—————-org.apache.shiro.web.filter.authz.SslFilter
    *@see user—————org.apache.shiro.web.filter.authz.UserFilter
    * @see =========================================================================================================
    * @see 3)通常可将这些过滤器分为两组
    * @see anon,authc,authcBasic,user是第一组认证过滤器
    * @see perms,port,rest,roles,ssl是第二组授权过滤器
    * @see 注意user和authc不同:当应用开启了rememberMe时,用户下次访问时可以是一个user,但绝不会是authc,因为authc是需要重新认证的
    * @see user表示用户不一定已通过认证,只要曾被Shiro记住过登录状态的用户就可以正常发起请求,比如rememberMe
    * @see 说白了,以前的一个用户登录时开启了rememberMe,然后他关闭浏览器,下次再访问时他就是一个user,而不会authc
    * @see ==========================================================================================================
    * @see 4)举几个例子
    * @see /admin=authc,roles[admin] 表示用户必需已通过认证,并拥有admin角色才可以正常发起’/admin’请求
    * @see /edit=authc,perms[admin:edit] 表示用户必需已通过认证,并拥有admin:edit权限才可以正常发起’/edit’请求
    * @see /home=user 表示用户不一定需要已经通过认证,只需要曾经被Shiro记住过登录状态就可以正常发起’/home’请求
    * @see ==========================================================================================================
    * @see 5)各默认过滤器常用如下(注意URL Pattern里用到的是两颗星,这样才能实现任意层次的全匹配)
    * @see /admins/**=anon 无参,表示可匿名使用,可以理解为匿名用户或游客
    * @see /admins/user/**=authc 无参,表示需认证才能使用
    * @see /admins/user/**=authcBasic 无参,表示httpBasic认证
    * @see /admins/user/**=user 无参,表示必须存在用户,当登入操作时不做检查
    * @see /admins/user/**=ssl 无参,表示安全的URL请求,协议为https
    * @see /admins/user/*=perms[user:add:]
    * @see 参数可写多个,多参时必须加上引号,且参数之间用逗号分割,如/admins/user/*=perms[“user:add:,user:modify:*”]
    * @see 当有多个参数时必须每个参数都通过才算通过,相当于isPermitedAll()方法
    * @see /admins/user/**=port[8081]
    * @see 当请求的URL端口不是8081时,跳转到schemal://serverName:8081queryString
    * @see 其中schmal是协议http或https等,serverName是你访问的Host,8081是Port端口,queryString是你访问的URL里的后面的参数
    * @see /admins/user/**=rest[user]
    * @see 根据请求的方法,相当于/admins/user/**=perms[user:method],其中method为post,get,delete等
    * @see /admins/user/**=roles[admin]
    * @see 参数可写多个,多个时必须加上引号,且参数之间用逗号分割,如/admins/user/**=roles[“admin,guest”]
    * @see 当有多个参数时必须每个参数都通过才算通过,相当于hasAllRoles()方法
    * @see

    http://liureying.blog.163.com/blog/static/61513520136205574873/

    spring中 shiro logout 配置方式
    有两种方式实现logout
    1. 普通的action中 实现自己的logout方法,取到Subject,然后logout
    这种需要在ShiroFilterFactoryBean 中配置 filterChainDefinitions
    对应的action的url为a

    # some example chain definitions:
    /index.htm = anon
    /logout = anon
    /unauthed = anon
    /console/** = anon
    /css/** = anon
    /js/** = anon
    /lib/** = anon
    /admin/** = authc, roles[admin]
    /docs/** = authc, perms[document:read]
    /** = authc
    # more URL-to-FilterChain definitions here
    使用shiro提供的logout filter
    需要定义 相应的bean

    然后将相应的url filter配置为logout如下

    
                
                    # some example chain definitions:
                    /index.htm = anon
                    /logout = logout
                    /unauthed = anon
                    /console/** = anon
                    /css/** = anon
                    /js/** = anon
                    /lib/** = anon
                    /admin/** = authc, roles[admin]
                    /docs/** = authc, perms[document:read]
                    /** = authc
                    # more URL-to-FilterChain definitions here
                
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    注:anon,authcBasic,auchc,user是认证过滤器,perms,roles,ssl,rest,port是授权过滤器

    最终 各种参数配置详解
    anon:例子/admins/**=anon 没有参数,表示可以匿名使用。
    authc:例如/admins/user/**=authc表示需要认证(登录)才能使用,没有参数
    roles:例子/admins/user/=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,例如admins/user/=roles[“admin,guest”],每个参数通过才算通过,相当于hasAllRoles()方法。
    perms:例子/admins/user/=perms[user:add:],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,例如/admins/user/=perms[“user:add:,user:modify:*”],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。
    rest:例子/admins/user/=rest[user],根据请求的方法,相当于/admins/user/=perms[user:method] ,其中method为post,get,delete等。
    port:例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString
    是你访问的url里的?后面的参数。
    authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证
    ssl:例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https
    user:例如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查
    注:anon,authcBasic,auchc,user是认证过滤器,
    perms,roles,ssl,rest,port是授权过滤器

  • 相关阅读:
    使用Apache HttpClient爬取网页内容的详细步骤解析与案例示例
    Flex布局的三个属性要深刻理解!
    深度解读GPT基本原理
    VALSE2023-快速总结
    Python学习 - 类与对象
    烧脑问题解决办法:如何选择一款合适自己的手机流量卡
    Linux新手教程||Linux vi/vim
    STP简介
    数论——扩展欧几里得算法
    2022杭电多校八 1007-Darnassus(kruscal)
  • 原文地址:https://blog.csdn.net/m0_67401270/article/details/126516448