springmvc+spring+mybatis+maven项目集成shiro进行用户权限控制

[java] view plain copy
  1. 项目结构:  

springmvc+spring+mybatis+maven项目集成shiro进行用户权限控制

1、maven项目的pom中引入shiro所需的jar包依赖关系

[html] view plain copy
  1. <dependency>  
  2.     <groupId>javax.servlet</groupId>  
  3.     <artifactId>javax.servlet-api</artifactId>  
  4.     <version>3.0.1</version>  
  5. </dependency>  
  6. <dependency>  
  7.     <groupId>org.apache.shiro</groupId>  
  8.     <artifactId>shiro-core</artifactId>  
  9.     <version>1.2.4<version>  
  10. </dependency>  
  11. <dependency>  
  12.     <groupId>org.apache.shiro</groupId>  
  13.     <artifactId>shiro-web</artifactId>  
  14.     <version>1.2.4<version>  
  15.               </dependency>  
  16.               <dependency>  
  17.     <groupId>org.apache.shiro</groupId>  
  18.     <artifactId>shiro-spring</artifactId>  
  19.     <version>1.2.4<version>  
  20.               </dependency>  
  21. <dependency>  
  22.     <groupId>org.apache.shiro</groupId>  
  23.     <artifactId>shiro-ehcache</artifactId>  
  24.     <version>1.2.4<version>  
  25. </dependency>  

2、web项目的web.xml中引入shiro的配置信息以及配置文件

[html] view plain copy
  1. <context-param>  
  2.     <param-name>contextConfigLocation</param-name>  
  3.     <param-value>classpath:applicationContext.xml,classpath:spring-shiro.xml</param-value>  
  4. </context-param>  

增加shiro的filter

[html] view plain copy
  1.               <filter>  
  2.     <filter-name>shiroFilter</filter-name>  
  3.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  4.     <init-param>  
  5.        <param-name>targetBeanName</param-name>  
  6.        <param-value>shiroFilterFactoryBean</param-value>  
  7.                       </init-param>  
  8.               </filter>  
  9. <filter-mapping>  
  10.         <filter-name>shiroFilter</filter-name>  
  11.         <url-pattern>/*</url-pattern>  
  12. </filter-mapping>  

配置spring-shiro.xml文件


[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:mvc="http://www.springframework.org/schema/mvc"  
  5.        xmlns:context="http://www.springframework.org/schema/context"  
  6.        xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/beans  
  8.         http://www.springframework.org/schema/beans/spring-beans.xsd  
  9.         http://www.springframework.org/schema/context  
  10.         http://www.springframework.org/schema/context/spring-context.xsd  
  11.         http://www.springframework.org/schema/mvc  
  12.         http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
  13.         <bean id="shiroFilterFactoryBean" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
  14.             <property name="securityManager" ref="securityManager" />  
  15.             <property name="loginUrl" value="/login/toLoginPage"/>  
  16.             <property name="successUrl" value="/login/index"/>  
  17.             <property name="unauthorizedUrl" value="/modules/unan.html"/>  
  18.             <property name="filterChainDefinitions">  
  19.                 <value>  
  20. <!--                     后期实际应用可采取正则模糊匹配,但要避免包含了静态资源的路径导致加载静态资源时也执行这个权限验证 -->  
  21.                     /login/adminView=authc,resourceCheckFilter  
  22.                     /login/testView=authc,resourceCheckFilter  
  23.                     /login/guestView=authc,resourceCheckFilter  
  24.                     <!--     user 表示该方法支持remember的用户访问 -->  
  25.                     /login/rememberMethod=user  
  26.                     /permission/**=authc,resourceCheckFilter  
  27.                     /admin/**.html=authc,resourceCheckFilter  
  28.                     /admin/**.jsp=authc,resourceCheckFilter  
  29.                     /admin/user/**.html=authc,resourceCheckFilter  
  30.                     /admin/user/**.jsp=authc,resourceCheckFilter  
  31.                     /admin/menu/**.html=authc,resourceCheckFilter  
  32.                     /admin/menu/**.jsp=authc,resourceCheckFilter  
  33.                     <!--shiro不拦截首页 -->  
  34.                     /=anon  
  35.                     <!--                     shiro不拦截resources下的资源 -->  
  36.                     /resources/**=anon  
  37. <!--                     shiro不拦截modules下的资源 -->  
  38.                     /modules/**=anon  
  39. <!--                     shiro不拦截public下的资源 -->  
  40.                     /public/**=anon  
  41.                     /admin/**=anon  
  42.                     /user/**=anon  
  43. <!--                     此处login被上面的覆盖了,可能会执行shiro权限校验 -->  
  44.                     /login/**=anon  
  45. <!--                     /login/login=anon -->  
  46. <!--                     /error=anon -->  
  47.                     /admin=authc,roles[admin]  
  48.                     /noAuth=roles[noAuth]  
  49. <!--                     /**=authc -->  
  50.                 </value>  
  51.             </property>  
  52.     </bean>  
  53.   
  54.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
  55.         <!--设置自定义realm,实现用户认证以及授权的操作-->  
  56.         <property name="realm" ref="monitorRealm" />  
  57.         <!--         设置自定义的权限验证方法,用于判定用户是否能对特定的菜单进行操作 -->  
  58.         <property name="authorizer.permissionResolver" ref="permissionResolver"/>  
  59.         <!--         设置全局session超时时间 -->  
  60.         <property name="sessionManager" ref="sessionManager"></property>  
  61.         <!--         记住我配置 -->  
  62.         <property name="rememberMeManager" ref="rememberMeManager" />  
  63.     </bean>  
  64.     <!--     全局超时时间 -->  
  65.     <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">  
  66.         <property name="sessionDAO" ref="sessionDAO" />  
  67.         <!--         1800000 半小时  10000 十秒 -->  
  68.         <property name="globalSessionTimeout" value="1800000"/>  
  69.         <property name="sessionValidationScheduler" ref="sessionValidationScheduler" />     
  70.         <property name="sessionValidationSchedulerEnabled" value="true" />   
  71.     </bean>  
  72.     <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">  
  73.         <property name="activeSessionsCacheName" value="shiro-activeSessionCache" />  
  74.     </bean>   
  75.     <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">  
  76.         <!--         每半小时检查一次是否过期 -->  
  77.         <property name="interval" value="1800000" />  
  78.     </bean>  
  79.         <!--     shiro生命周期 -->  
  80.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />  
  81.     <!--自定义Realm 继承自AuthorizingRealm-->  
  82.     <bean id="monitorRealm" class="org.youme.realm.UserRealm">  
  83.         <!--         注入自定义密码校验方法,可在该bean中设置短时间内最大尝试次数 -->  
  84.         <property name="credentialsMatcher" ref="credentialsMatcher" />  
  85.         <property name="cachingEnabled" value="true" />  
  86.         <property name="authenticationCachingEnabled" value="true" />  
  87.         <property name="authenticationCacheName" value="authenticationCache" />  
  88.         <property name="authorizationCachingEnabled" value="true" />  
  89.         <property name="authorizationCacheName" value="authorizationCache" />  
  90.     </bean>  
  91.     <!-- 凭证匹配器 -->  
  92.     <bean id="credentialsMatcher"  
  93.         class="org.youme.util.RetryLimitHashedCredentialsMatcher">  
  94.         <constructor-arg ref="cacheManager" />  
  95.         <!--         此处设置短时间内出错次数 -->  
  96.         <property name="errorTimes" value="6"></property>  
  97.         <!--         设置SHIRO加密方式,需要和util里的加密方法保持一致 -->  
  98.         <property name="hashAlgorithmName" value="MD5" />  
  99.         <!--         设置SHIRO加密次数 -->  
  100.         <property name="hashIterations" value="3" />  
  101.         <property name="storedCredentialsHexEncoded" value="true" />  
  102.     </bean>  
  103.     <!-- securityManager -->  
  104.     <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">  
  105.         <property name="staticMethod"  
  106.                   value="org.apache.shiro.SecurityUtils.setSecurityManager" />  
  107.         <property name="arguments" ref="securityManager" />  
  108.     </bean>  
  109.   
  110.     <!-- Enable Shiro Annotations for Spring-configured beans.  Only run after -->  
  111.     <!-- the lifecycleBeanProcessor has run: -->  
  112.     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>  
  113.     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
  114.         <property name="securityManager" ref="securityManager"/>  
  115.     </bean>  
  116.     <!-- 缓存管理器 使用Ehcache实现 -->  
  117.     <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">  
  118.         <property name="cacheManagerConfigFile" value="classpath:spring-shiro-ehcache.xml" />  
  119.     </bean>  
  120.     <!--     URL权限验证方法 -->  
  121.     <bean id="resourceCheckFilter" class="org.youme.filter.ResourceCheckFilter">  
  122.         <!--         设置当前用户无权限访问当前链接时跳转的页面 -->  
  123.         <property name="unanUrl" value="modules/unan.html"></property>  
  124.     </bean>  
  125.     <bean id="permissionResolver" class="org.youme.permission.UrlPermissionResolver"/>  
  126.     <!-- remenberMe配置 -->  
  127.    <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">  
  128.        <constructor-arg value="rememberMe" />  
  129.        <property name="httpOnly" value="true" />  
  130.        <!-- 默认记住7天(单位:秒) -->  
  131.        <property name="maxAge" value="604800" />  
  132.    </bean>  
  133.    <!-- rememberMe管理器 -->  
  134.    <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">  
  135.        <property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}" />  
  136.        <property name="cookie" ref="rememberMeCookie" />  
  137.    </bean>  
  138. </beans>  

此处引入了spring-shiro-ehcache.xml文件

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ehcache name="shirocache">  
  3.   
  4.     <diskStore path="java.io.tmpdir" />  
  5.   
  6.     <!-- 登录记录缓存 锁定10分钟 -->  
  7.     <cache name="passwordRetryCache" eternal="false"  
  8.         timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false"  
  9.         statistics="true" maxBytesLocalHeap="10M">  
  10.     </cache>  
  11.   
  12.     <cache name="authorizationCache" eternal="false"  
  13.         timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false"  
  14.         statistics="true" maxBytesLocalHeap="10M">  
  15.     </cache>  
  16.   
  17.     <cache name="authenticationCache" eternal="false"  
  18.         timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false"  
  19.         statistics="true" maxBytesLocalHeap="10M">  
  20.     </cache>  
  21.   
  22.     <cache name="shiro-activeSessionCache" eternal="false"  
  23.         timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false"  
  24.         statistics="true" maxBytesLocalHeap="10M">  
  25.     </cache>  
  26.   
  27. </ehcache>  

实现spring-shiro中配置的自定义拦截器实现用户信息校验以及登录成功后授予相应的角色以及权限


 

[java] view plain copy
  1. package org.youme.realm;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5.   
  6.   
  7. import org.apache.shiro.SecurityUtils;  
  8. import org.apache.shiro.authc.AuthenticationException;  
  9. import org.apache.shiro.authc.AuthenticationInfo;  
  10. import org.apache.shiro.authc.AuthenticationToken;  
  11. import org.apache.shiro.authc.LockedAccountException;  
  12. import org.apache.shiro.authc.SimpleAuthenticationInfo;  
  13. import org.apache.shiro.authc.UnknownAccountException;  
  14. import org.apache.shiro.authc.UsernamePasswordToken;  
  15. import org.apache.shiro.authz.AuthorizationInfo;  
  16. import org.apache.shiro.authz.SimpleAuthorizationInfo;  
  17. import org.apache.shiro.realm.AuthorizingRealm;  
  18. import org.apache.shiro.session.Session;  
  19. import org.apache.shiro.subject.PrincipalCollection;  
  20. import org.apache.shiro.subject.Subject;  
  21. import org.apache.shiro.util.ByteSource;  
  22. import org.springframework.beans.factory.annotation.Autowired;  
  23. import org.youme.service.PermissionService;  
  24. import org.youme.service.ResourceService;  
  25. import org.youme.service.RoleService;  
  26. import org.youme.service.UserService;  
  27. public class UserRealm extends AuthorizingRealm{  
  28.       
  29.     @Autowired  
  30.         //项目中自己实现查询用户信息service  
  31.     UserService userService;  
  32.       
  33.     @Autowired  
  34.         //项目中自己实现查询角色信息service  
  35.     RoleService roleService;  
  36.       
  37.     @Autowired  
  38.         //暂时没用这个service  
  39.     ResourceService resourceService;  
  40.       
  41.     @Autowired  
  42.         //项目中自己实现查询权限信息service  
  43.     PermissionService permissionService;  
  44.       
  45.     @Override  
  46.     /**  
  47.      * 登录成功后给用户授予系统中特定权限  
[java] view plain copy
  1.      * */  
  2.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  3.         String key = "AUTHORIZATION_INFO";  
  4.         Subject subject = SecurityUtils.getSubject();  
  5.         Session session = subject.getSession(false);  
  6.         SimpleAuthorizationInfo authorizationInfo = (SimpleAuthorizationInfo) session.getAttribute(key);  
  7.         if (!subject.isAuthenticated() || authorizationInfo == null) {  
  8.             String username = (String) principals.getPrimaryPrincipal();  
  9.             HashMap map = new HashMap();  
  10.             map.put("account", username);  
  11.             List users =  userService.getUserForLogin(map);  
  12.             map = (HashMap)users.get(0);  
  13.             Object userId = map.get("id");  
  14.             map.put("userId", userId);  
  15.             map.put("isWork""Y");  
  16.             List roles = roleService.getRolesForLogin(map);  
  17.             authorizationInfo = new SimpleAuthorizationInfo();  
  18.             authorizationInfo.addRoles(roles);  
  19.             if(userId!=null){  
  20.                 //根据当前用户ID获取其生效的菜单权限并给该用户授权  
  21.                 map.clear();  
  22.                 map.put("userId", userId);  
  23.                 map.put("isWork""Y");  
  24.                 //此处返回list<String>类型的权限  
  25.                 List permissions = permissionService.findPermissionByMap(map);  
  26.                 authorizationInfo.addStringPermissions(permissions);  
  27.             }  
  28.             session.setAttribute(key, authorizationInfo);  
  29.         }  
  30.         return authorizationInfo;  
  31.     }  
  32.   
  33.     @Override  
  34.     /** 
  35.      * 用户登录密码校验方法 
  36.      * */  
  37.     protected AuthenticationInfo doGetAuthenticationInfo(  
  38.             AuthenticationToken token) throws AuthenticationException {  
  39.         UsernamePasswordToken upToken = (UsernamePasswordToken) token;  
  40.         String account = upToken.getUsername();  
  41.         HashMap map = new HashMap();  
  42.         map.put("account", account);  
  43.         List users =  userService.getUserForLogin(map);  
  44.         if(users==null||users.size()==0){  
  45.             throw new UnknownAccountException();  
  46.         }else{  
  47.             map = (HashMap)users.get(0);  
  48.             Object IsLocked = map.get("isLocked");  
  49.             if(null!=IsLocked&&"Y".equals(IsLocked.toString())){  
  50.                 //账户被锁定  
  51.                 throw new LockedAccountException();  
  52.             }  
  53.             SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(map.get("account"),   
  54.                     map.get("passwd"),   
  55.                     getClass().getName());  
  56.             //第一种加密方式  
  57.             //系统设置固定的加密盐方式  
  58. //          info.setCredentialsSalt(ByteSource.Util.bytes(map.get("name")));  
  59.             //第二种方式:加密盐由系统随机生成,保存在数据库中,查询用户信息时需要将该随机盐一同查询出来  
  60.             Object randomSalt = map.get("salt") ;//此处值由用户表获取  
  61.             info.setCredentialsSalt(ByteSource.Util.bytes(randomSalt));  
  62.             return info;  
  63.         }  
  64.     }  
  65.   
  66. }  


 登录方法中将用户名和密码传递给UsernamePasswordToken,通过shiro提供的login方法即可实现登录逻辑

[java] view plain copy
  1.               Subject subject = SecurityUtils.getSubject();  
  2. //前台页面中传递过来的用户账户  
  3. Object o1 = map.get("account");  
  4. //前台页面传递过来的用户密码  
  5. Object o2 = map.get("password");  
  6. //前台是否选择记住我按钮  
  7. Object rememberMe = map.get("rememberMe");  
  8.               //登录反馈给前台的结果  
  9.               Map<String, Object> result = new HashMap<String,Object>();   
  10.               UsernamePasswordToken token = new UsernamePasswordToken(o1.toString(),o2.toString());  
  11.     try {  
  12.         if("Y".equals(rememberMe+"")){  
  13.             //记住我  
  14.             token.setRememberMe(true);    
  15.         }  
[java] view plain copy
  1. //登录方法  
[java] view plain copy
  1.     subject.login(token);  
  2.     // 在web应用中,subject.getSession()和request.getSession()作用一样  
  3.     // session也一样,放入subject.getSession()和request.getSession()中的对象是共享的  
  4.     // 但是为了兼容性,推荐使用subject.getSession()  
  5.     org.apache.shiro.session.Session session = subject.getSession(false);  
  6.     List users =  userService.getUserForLogin(map);  
  7.     map = (HashMap)users.get(0);  
  8.     session.setAttribute("user", map);  
  9. catch (UnknownAccountException  uae) {  
  10.     result.put("status"false);  
  11.     result.put("errorMsg""用户名或密码错误");  
  12.     log_.info("There is no user with username of :"+token.getPrincipal());  
  13.     return result;  
  14. }catch (IncorrectCredentialsException  ice) {  
  15.     result.put("status"false);  
  16.     result.put("errorMsg""用户名或密码错误");  
  17.     log_.info("Password for account " + token.getPrincipal() + " was incorrect!");    
  18.     return result;  
  19. }catch (LockedAccountException lae) {   
  20.     result.put("status"false);  
  21.     result.put("errorMsg""当前登录用户 :"+token.getPrincipal()+"被锁定,请联系系统管理员!");  
  22.     log_.info("The account for username " + token.getPrincipal() + " is locked");  
  23.     return result;  
  24. }catch(ExcessiveAttemptsException eae){  
  25.     result.put("status"false);  
  26.     result.put("errorMsg""登录失败次数超过系统最大次数,请稍后重试!");  
  27.     log_.info("登录失败次数超过系统最大次数,请稍后重试!");  
  28.     //此处可对用户账户进行锁定操作  
  29.     return result;  
  30. catch (Exception e) {  
  31.     result.put("status"false);  
  32.     result.put("errorMsg""登录过程出现异常,请联系管理员!");  
  33.     e.printStackTrace();  
  34.     return result;  
  35. }  
  36. //请求成功后返回JSON格式的用户名  
  37. result.put("status"true);  
  38. result.put("errorMsg", token.getPrincipal()+"登录成功!");  

UrlPermissionResolver将url类型的链接转换成shiro中使用的Permission实现类Urlpermission

[java] view plain copy
  1. package org.youme.permission;  
  2.   
  3. import org.apache.shiro.authz.Permission;  
  4. import org.apache.shiro.authz.permission.PermissionResolver;  
  5. import org.apache.shiro.authz.permission.WildcardPermission;  
  6.   
  7. public class UrlPermissionResolver implements PermissionResolver {  
  8.   
  9.     public Permission resolvePermission(String permissionString) {  
  10.         if(permissionString!=null){  
  11.             if(permissionString.startsWith("/")){  
  12.                 return new Urlpermission(permissionString);  
  13.             }  
  14.             return new WildcardPermission(permissionString);  
  15.         }  
  16.         return new Urlpermission("");  
  17.     }  
  18.   
  19. }  

Urlpermission实现shiro的permission接口

[java] view plain copy
  1. package org.youme.permission;  
  2.   
  3. import org.apache.shiro.authz.Permission;  
  4. import org.apache.shiro.util.AntPathMatcher;  
  5. import org.apache.shiro.util.PatternMatcher;  
  6.   
  7. public class Urlpermission implements Permission {  
  8.   
  9.     private String url ;  
  10.       
  11.     public String getUrl() {  
  12.         return url;  
  13.     }  
  14.   
  15.     public void setUrl(String url) {  
  16.         this.url = url;  
  17.     }  
  18.   
  19.     public Urlpermission() {  
  20.     }  
  21.     public Urlpermission(String url) {  
  22.         this.url = url;  
  23.     }  
  24.     public boolean implies(Permission p) {  
  25.         if(!(p instanceof Urlpermission))return false;  
  26.         Urlpermission up = (Urlpermission)p;  
  27.         PatternMatcher matcher = new AntPathMatcher();  
  28.         return matcher.matches(url, up.getUrl());  
  29.     }  
  30.       
  31.       
  32. }  

spring-shiro配置文件中定义的ResourceCheckFilter用于判定用户是否能够访问当前链接/菜单

[java] view plain copy
  1. package org.youme.filter;  
  2.   
  3. import java.util.logging.Logger;  
  4.   
  5. import javax.servlet.ServletRequest;  
  6. import javax.servlet.ServletResponse;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. import org.apache.shiro.subject.Subject;  
  11. import org.apache.shiro.web.filter.AccessControlFilter;  
  12.   
  13. public class ResourceCheckFilter extends AccessControlFilter {  
  14.       
  15.     private Logger log_ = Logger.getLogger(ResourceCheckFilter.class.getName());  
  16.     /** 
  17.      * 未授权用户访问时跳转的页面路径 
  18.      * */  
  19.     private String unanUrl;  
  20.   
  21.     public String getUnanUrl() {  
  22.         return unanUrl;  
  23.     }  
  24.   
  25.     public void setUnanUrl(String unanUrl) {  
  26.         this.unanUrl = unanUrl;  
  27.     }  
  28.   
  29.     /** 
  30.      * 判定用户是否具有特定权限 
  31.      * */  
  32.     protected boolean isAccessAllowed(ServletRequest req,  
  33.             ServletResponse res, Object arg2) throws Exception {  
  34.         //获取当前登录用户  
  35.         Subject subject = getSubject(req, res);  
  36.         String url = getPathWithinApplication(req);  
  37.         return subject.isPermitted(url);  
  38.     }  
  39.   
  40.     /** 
  41.      *用户不具备当前菜单访问权限时的处理方法  
  42.      * */  
  43.     protected boolean onAccessDenied(ServletRequest req, ServletResponse res)  
  44.             throws Exception {  
  45.         HttpServletResponse response = (HttpServletResponse)res;  
  46.         HttpServletRequest request = (HttpServletRequest)req;  
  47.         response.sendRedirect(request.getContextPath()+"/"+unanUrl);  
  48.         return false;  
  49.     }  
  50.   
  51. }  

spring-shiro定义的RetryLimitHashedCredentialsMatcher用于限制短时间内密码输错的次数

[java] view plain copy
  1. package org.youme.util;  
  2.   
  3. import java.util.concurrent.atomic.AtomicInteger;  
  4.   
  5. import org.apache.shiro.authc.AuthenticationInfo;  
  6. import org.apache.shiro.authc.AuthenticationToken;  
  7. import org.apache.shiro.authc.ExcessiveAttemptsException;  
  8. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;  
  9. import org.apache.shiro.cache.Cache;  
  10. import org.apache.shiro.cache.CacheManager;  
  11. /** 
  12.  * 自定义密码校验,在本方法中设置最大出错次数 
  13.  * */  
  14. public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher  {  
  15.       
  16.     private int errorTimes ;  
  17.       
  18.     public int getErrorTimes() {  
  19.         return errorTimes;  
  20.     }  
  21.   
  22.     public void setErrorTimes(int errorTimes) {  
  23.         this.errorTimes = errorTimes;  
  24.     }  
  25.   
  26.     private Cache<String, AtomicInteger> passwordRetryCache;  
  27.       
  28.      public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {    
  29.          passwordRetryCache = cacheManager.getCache("passwordRetryCache");   
  30.      }  
  31.        
  32.      public boolean doCredentialsMatch(AuthenticationToken token,AuthenticationInfo info){  
  33.          String username = (String) token.getPrincipal();    
  34.          AtomicInteger retryCount = passwordRetryCache.get(username);    
  35.          if(retryCount == null){  
  36.              retryCount = new AtomicInteger(0);   
  37.              passwordRetryCache.put(username, retryCount);  
  38.          }  
  39.          //重复输错密码5次时需要等十分钟后重试  
  40.          int total = 0 ;  
  41.          if(errorTimes == 0){  
  42.              total = 5;  
  43.          }else{  
  44.              total = errorTimes;  
  45.          }  
  46.          if (retryCount.incrementAndGet() > total) {    
  47.              throw new ExcessiveAttemptsException();    
  48.          }  
  49.          boolean matches = super.doCredentialsMatch(token, info);    
  50.          if(matches){  
  51.              passwordRetryCache.remove(username);  
  52.          }  
  53.          return matches;  
  54.      }  
  55. }