spring boot整合shiro
一、需要的依赖包 <!--shiro的版本--> <properties> <org.apache.shiro.version>1.3.2</org.apache.shiro.version> </properties> <!--shiro--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${org.apache.shiro.version}</version> /dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${org.apache.shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${org.apache.shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>${org.apache.shiro.version}</version> </dependency> 二、添加ehcache <?xmlversion="1.0"encoding="UTF-8"?> <!DOCTYPExml> <ehcacheupdateCheck="false"name="shiroCache"> <!--http://ehcache.org/ehcache.xml--> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> <!--登录记录缓存锁定10分钟--> <cachename="passwordRetryCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="1800" overflowToDisk="false" statistics="true"> </cache> <cachename="authorizationCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> <cachename="authenticationCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> <cachename="shiro-activeSessionCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> </ehcache> 三、创建一个realm publicclassShiroRealmextendsAuthorizingRealm{ @Autowired privateUserBizbiz; @Override protectedAuthorizationInfodoGetAuthorizationInfo(PrincipalCollectionprincipals){ //获取用户权限 SimpleAuthorizationInfoauthorizationInfo=newSimpleAuthorizationInfo(); authorizationInfo.setRoles(角色集合); authorizationInfo.setStringPermissions(权限集合); returnauthorizationInfo; } @Override protectedAuthenticationInfodoGetAuthenticationInfo(AuthenticationTokentoken)throwsAuthenticationException{ returnnewSimpleAuthenticationInfo(获取到的用户账号, 获取到的用户密码,ByteSource.Util.bytes(user.getUserNo()+Constants.token.salt),getName()); } } 四、添加验证器 publicclassPlatFormCredentialsMatcherextendsHashedCredentialsMatcher{ @Autowired privateUserServiceservice; @Autowired privateEhCacheManagershiroEhcacheManager; @Override publicbooleandoCredentialsMatch(AuthenticationTokentoken,AuthenticationInfoinfo){ Cache<String,AtomicInteger>passwordRetryCache=shiroEhcacheManager.getCache("passwordRetryCache"); Stringuserno=(String)token.getPrincipal(); //retrycount+1 AtomicIntegerretryCount=passwordRetryCache.get(userno); if(retryCount==null){ retryCount=newAtomicInteger(0); passwordRetryCache.put(userno,retryCount); } if(retryCount.incrementAndGet()>5){ //ifretrycount>5throw thrownewExcessiveAttemptsException(); } booleanmatches=super.doCredentialsMatch(token,info); if(matches){ //clearretrycount passwordRetryCache.remove(userno); Result<User>userResult=service.findByUserNo(userno); //根据登录名查询用户 Subjectsubject=SecurityUtils.getSubject(); Sessionsession=subject.getSession(); session.setAttribute("user",userResult.getResultData()); } returnmatches; } } 五、添加shiro配置 @Configuration publicclassShiroConfiguration{ privatestaticMap<String,String>filterChainDefinitionMap=newLinkedHashMap<String,String>(); @Bean(name="ShiroRealm") publicShiroRealmgetShiroRealm(@Qualifier("credentialsMatcher")CredentialsMatchermatcher){ ShiroRealmshiroRealm=newShiroRealm(); shiroRealm.setCredentialsMatcher(matcher); returnshiroRealm; } @Bean(name="shiroEhcacheManager") publicEhCacheManagergetEhCacheManager(){ EhCacheManagerem=newEhCacheManager(); em.setCacheManagerConfigFile("classpath:ehcache/ehcache-shiro.xml"); returnem; } @Bean(name="credentialsMatcher") publicPlatFormCredentialsMatchergetCredentialsMatcher(){ PlatFormCredentialsMatcherplatFormCredentialsMatcher=newPlatFormCredentialsMatcher(); platFormCredentialsMatcher.setHashAlgorithmName("MD5"); platFormCredentialsMatcher.setHashIterations(2); platFormCredentialsMatcher.setStoredCredentialsHexEncoded(true); returnplatFormCredentialsMatcher; } @Bean(name="lifecycleBeanPostProcessor") publicLifecycleBeanPostProcessorgetLifecycleBeanPostProcessor(){ returnnewLifecycleBeanPostProcessor(); } @Bean publicDefaultAdvisorAutoProxyCreatorgetDefaultAdvisorAutoProxyCreator(){ DefaultAdvisorAutoProxyCreatordaap=newDefaultAdvisorAutoProxyCreator(); daap.setProxyTargetClass(true); returndaap; } @Bean(name="securityManager") publicDefaultWebSecurityManagergetDefaultWebSecurityManager(@Qualifier("ShiroRealm")ShiroRealmshiroRealm){ DefaultWebSecurityManagerdwsm=newDefaultWebSecurityManager(); dwsm.setRealm(shiroRealm); dwsm.setCacheManager(getEhCacheManager()); returndwsm; } @Bean publicAuthorizationAttributeSourceAdvisorgetAuthorizationAttributeSourceAdvisor(@Qualifier("securityManager")DefaultWebSecurityManagerdwsm){ AuthorizationAttributeSourceAdvisoraasa=newAuthorizationAttributeSourceAdvisor(); aasa.setSecurityManager(dwsm); returnnewAuthorizationAttributeSourceAdvisor(); } @Bean(name="shiroFilter") publicShiroFilterFactoryBeangetShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManagerdwsm){ ShiroFilterFactoryBeanshiroFilterFactoryBean=newShiroFilterFactoryBean(); shiroFilterFactoryBean .setSecurityManager(dwsm); shiroFilterFactoryBean.setLoginUrl("/login"); shiroFilterFactoryBean.setSuccessUrl("/admin/index"); shiroFilterFactoryBean.setUnauthorizedUrl("/login"); filterChainDefinitionMap.put("/login","authc"); filterChainDefinitionMap.put("/BJUI/**","anon"); filterChainDefinitionMap.put("/platform/**","anon"); filterChainDefinitionMap.put("/admin/course/category/list","perms[user:view]"); filterChainDefinitionMap.put("/admin/course/category/edit","perms[user:update]"); filterChainDefinitionMap.put("/admin/course/category/update","perms[user:update]"); filterChainDefinitionMap.put("/admin/course/category/add","perms[user:add]"); filterChainDefinitionMap.put("/admin/**","anon"); shiroFilterFactoryBean .setFilterChainDefinitionMap(filterChainDefinitionMap); returnshiroFilterFactoryBean; } /** *FilterRegistrationBean *@return */ @Bean publicFilterRegistrationBeanfilterRegistrationBean(){ FilterRegistrationBeanfilterRegistration=newFilterRegistrationBean(); filterRegistration.setFilter(newDelegatingFilterProxy("shiroFilter")); filterRegistration.setEnabled(true); filterRegistration.addUrlPatterns("/*"); filterRegistration.setDispatcherTypes(DispatcherType.REQUEST); returnfilterRegistration; } }