Spring MVC + Shiro 实现权限验证

MAVEN的pom.xml 引入shiro:


[html]  view plain  copy
  1. <dependency>  
  2.             <groupId>org.apache.shiro</groupId>  
  3.             <artifactId>shiro-spring</artifactId>  
  4.             <version>1.2.5</version>  
  5.         </dependency>  
  6.           
  7.           
  8.         <!-- http://mvnrepository.com/artifact/org.apache.shiro/shiro-ehcache -->  
  9.         <dependency>  
  10.             <groupId>org.apache.shiro</groupId>  
  11.             <artifactId>shiro-ehcache</artifactId>  
  12.             <version>1.2.5</version>  
  13.         </dependency>  
  14.                   
  15.   
  16.         <dependency>  
  17.             <groupId>org.apache.shiro</groupId>  
  18.             <artifactId>shiro-core</artifactId>  
  19.             <version>1.2.5</version>  
  20.         </dependency>  
  21.           
  22.         <!-- http://mvnrepository.com/artifact/org.apache.shiro/shiro-web -->  
  23.         <dependency>  
  24.             <groupId>org.apache.shiro</groupId>  
  25.             <artifactId>shiro-web</artifactId>  
  26.             <version>1.2.5</version>  
  27.         </dependency>  
  28.                   


web.xml 中添加shiro的过滤器


[html]  view plain  copy
  1.   <!-- 配置Shiro过滤器,先让Shiro过滤系统接收到的请求 -->    
  2. <!-- 这里filter-name必须对应applicationContext.xml中定义的<bean id="shiroFilter"/> -->    
  3. <!-- 使用[/*]匹配所有请求,保证所有的可控请求都经过Shiro的过滤 -->    
  4. <!-- 通常会将此filter-mapping放置到最前面(即其他filter-mapping前面),以保证它是过滤器链中第一个起作用的 -->    
  5. <filter>    
  6.     <filter-name>shiroFilter</filter-name>    
  7.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>    
  8.     <init-param>    
  9.     <!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->    
  10.     <param-name>targetFilterLifecycle</param-name>    
  11.     <param-value>true</param-value>    
  12.     </init-param>    
  13. </filter>    
  14. <filter-mapping>    
  15.         <filter-name>shiroFilter</filter-name>    
  16.         <url-pattern>/*</url-pattern>    
  17. </filter-mapping>  
  18.      



Spring 配置文件中添加shiro的配置


[html]  view plain  copy
  1. <!-- shiro config  -->  
  2.     
  3.     
  4.   <!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的ShiroDbRealm.java -->    
  5. <bean id="myRealm" class="com.blog.shiro.entity.BaseRealm"/>    
  6.     
  7. <!-- Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session -->    
  8. <!-- 即<property name="sessionMode" value="native"/>,详细说明见官方文档 -->    
  9. <!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->    
  10. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">    
  11.     <property name="realm" ref="myRealm"/>    
  12. </bean>    
  13.     
  14. <!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->    
  15. <!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->    
  16. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">    
  17.     <!-- Shiro的核心安全接口,这个属性是必须的 -->    
  18.     <property name="securityManager" ref="securityManager"/>    
  19.     <!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->    
  20.     <property name="loginUrl" value="/company/admin/login.html"/>    
  21.     <!-- 登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在LoginController里硬编码为main.jsp了) -->    
  22.     <!-- <property name="successUrl" value="/system/main"/> -->    
  23.     <!-- 用户访问未对其授权的资源时,所显示的连接 -->    
  24.     <!-- 若想更明显的测试此属性可以修改它的值,如unauthor.jsp,然后用[玄玉]登录后访问/admin/listUser.jsp就看见浏览器会显示unauthor.jsp -->    
  25.     <property name="unauthorizedUrl" value="/admin/index.html"/>    
  26.     <!-- Shiro连接约束配置,即过滤链的定义 -->    
  27.     <!-- 此处可配合我的这篇文章来理解各个过滤连的作用http://blog.youkuaiyun.com/jadyer/article/details/12172839 -->    
  28.     <!-- 下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->    
  29.     <!-- anon:它对应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示参数,比方说login.jsp?main这种 -->    
  30.     <!-- authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->    
  31.       
  32.       
  33.      <property name="filters">  
  34.         <map>  
  35.             <entry key="permission">  
  36.               <bean class="com.blog.shiro.filters.RoleAuthorizationFilter">  
  37.               </bean>  
  38.             </entry>  
  39.         </map>  
  40.     </property>  
  41.       
  42.      
  43.       
  44.     <property name="filterChainDefinitions">    
  45.         <value>    
  46.           
  47.             <!-- /admin/login=anon    
  48.              /mydemo/login=anon    
  49.              /mydemo/getVerifyCodeImage=anon    
  50.              /main**=authc    
  51.              /user/info**=authc    
  52.              /admin/listUser**=authc,perms[admin:manage]    
  53.              -->  
  54.              /admin/**=permission  
  55.                
  56.         </value>    
  57.     </property>  
  58. </bean>    
  59.     
  60. <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->    
  61. <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>    
  62.     
  63. <!-- 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 -->    
  64. <!-- 配置以下两个bean即可实现此功能 -->    
  65. <!-- Enable Shiro Annotations for Spring-configured beans. Only run after the lifecycleBeanProcessor has run -->    
  66. <!-- 由于本例中并未使用Shiro注解,故注释掉这两个bean(个人觉得将权限通过注解的方式硬编码在程序中,查看起来不是很方便,没必要使用) -->    
  67. <!--     
  68. <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>    
  69.   <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">    
  70.     <property name="securityManager" ref="securityManager"/>    
  71.   </bean>    
  72. -->  
  73.     
  74.     
  75.     
  76.     

注意:上面的com.blog.shiro.entity.BaseRealm 属于自己定制的用于登录用户的授权。com.blog.shiro.filters.RoleAuthorizationFilter是自己定义的Shiro的过滤器,进行授权验证。filterChainDefinitions用于指定要拦截URL 需特别注意的是Shiro的默认filter和自定义filter的使用。


下面贴出自己的一个简单的用户登录的权限验证的部分代码。登录页面就不贴了


首先是登录的处理方法:
[java]  view plain  copy
  1. @RequestMapping(value={"/admin/login"},method={RequestMethod.POST})  
  2.     public String login(String username,String password, ModelMap model){  
  3.           
  4.         if(Checker.isEmpty(username) || Checker.isEmpty(password)){  
  5.               
  6.             model.put("mesage""登录失败:请检查您的用户名和密码!");  
  7.         }  
  8.           
  9.         Map<String, Object> map = new HashMap<String,Object>();  
  10.         map.put("username", username);  
  11.         List<User> users = userDaoImpl.findListBy(map);  
  12.           
  13.         if(users.size() > 0){  
  14.               
  15.             User user = users.get(0);  
  16.             if(user.getpassword().equals(password)){  
  17.                 //从SecurityUtils中取得subject   
  18.                 Subject subject = SecurityUtils.getSubject();  
  19.                 //创建Token  
  20.                 UsernamePasswordToken token = new UsernamePasswordToken(user.getusername(),user.getpassword());  
  21.                   
  22.                 // 使用token登录  
  23.                 subject.login(token);  
  24.                 return  "redirect:/admin/index.html";  
  25.             }else{  
  26.                 model.put("mesage""登录失败:请检查您的用户名和密码!");  
  27.             }  
  28.               
  29.         }else{  
  30.             model.put("mesage""登录失败:请检查您的用户名和密码!");  
  31.         }  
  32.         return "login";  
  33.     }  


BaseRealm.java的实现



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

注意:我这里使用的是URI来进行权限的管理,也就是说
simpleAuthorInfo.addStringPermission("/admin/index.html");  
            simpleAuthorInfo.addStringPermission("/admin/left.html");  
            simpleAuthorInfo.addStringPermission("/admin/info.html");  
            simpleAuthorInfo.addStringPermission("/admin/user/list.html");
这部分代码进行的是授权,意思为验证成功的用户有访问这些URI的权利 没有访问其他URI的权利,下面的filter将根据这个授权进行来开放URI给用户,
授权需根据数据库进行授权。 有时间将会有对于通用授权的实现单独写一章。


自定义filter的代码实现:


[java]  view plain  copy
  1. package com.blog.shiro.filters;  
  2.   
  3. import javax.servlet.ServletRequest;  
  4. import javax.servlet.ServletResponse;  
  5. import javax.servlet.http.HttpServletRequest;  
  6.   
  7. import org.apache.shiro.subject.Subject;  
  8. import org.apache.shiro.web.filter.authz.AuthorizationFilter;  
  9.   
  10. public class RoleAuthorizationFilter extends AuthorizationFilter {  
  11.   
  12.     @Override  
  13.     protected boolean isAccessAllowed(ServletRequest request,  
  14.             ServletResponse response, Object object) throws Exception {  
  15.         // 获取请求的资源(即请求的URI)  
  16.         HttpServletRequest httpReq = (HttpServletRequest) request;  
  17.         String uri = httpReq.getRequestURI();  
  18.           
  19.         //根据请求响应获取已登录的Subject对象。  
  20.         Subject subject = getSubject(request, response);  
  21.           
  22.         // 判断登录的用户是否有此权限  
  23.         return subject.isPermitted(uri);  
  24.     }  
  25.   
  26. }  




shiro的使用异常简单方便,如有任何问题请留言。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值