原 spring boot整合shiro
2357 | 0 | 0
一、需要的依赖包
<!--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
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE xml> <ehcache updateCheck="false" name="shiroCache"> <!-- http://ehcache.org/ehcache.xml --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> <!-- 登录记录缓存 锁定10分钟 --> <cache name="passwordRetryCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="1800" overflowToDisk="false" statistics="true"> </cache> <cache name="authorizationCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> <cache name="authenticationCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> <cache name="shiro-activeSessionCache" maxEntriesLocalHeap="2000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" overflowToDisk="false" statistics="true"> </cache> </ehcache>
三、创建一个realm
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserBiz biz;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//获取用户权限
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.setRoles(角色集合);
authorizationInfo.setStringPermissions(权限集合);
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
return new SimpleAuthenticationInfo(获取到的用户账号,
获取到的用户密码, ByteSource.Util.bytes(user.getUserNo() + Constants.token.salt), getName());
}
}四、添加验证器
public class PlatFormCredentialsMatcher extends HashedCredentialsMatcher {
@Autowired
private UserService service;
@Autowired
private EhCacheManager shiroEhcacheManager;
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
Cache<String, AtomicInteger> passwordRetryCache = shiroEhcacheManager.getCache("passwordRetryCache");
String userno = (String) token.getPrincipal();
// retry count + 1
AtomicInteger retryCount = passwordRetryCache.get(userno);
if (retryCount == null) {
retryCount = new AtomicInteger(0);
passwordRetryCache.put(userno, retryCount);
}
if (retryCount.incrementAndGet() > 5) {
// if retry count > 5 throw
throw new ExcessiveAttemptsException();
}
boolean matches = super.doCredentialsMatch(token, info);
if (matches) {
// clear retry count
passwordRetryCache.remove(userno);
Result<User> userResult = service.findByUserNo(userno);
// 根据登录名查询用户
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.setAttribute("user", userResult.getResultData());
}
return matches;
}
}五、添加shiro配置
@Configuration
public class ShiroConfiguration {
private static Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
@Bean(name = "ShiroRealm")
public ShiroRealm getShiroRealm(@Qualifier("credentialsMatcher") CredentialsMatcher matcher) {
ShiroRealm shiroRealm = new ShiroRealm();
shiroRealm.setCredentialsMatcher(matcher);
return shiroRealm;
}
@Bean(name = "shiroEhcacheManager")
public EhCacheManager getEhCacheManager() {
EhCacheManager em = new EhCacheManager();
em.setCacheManagerConfigFile("classpath:ehcache/ehcache-shiro.xml");
return em;
}
@Bean(name="credentialsMatcher")
public PlatFormCredentialsMatcher getCredentialsMatcher(){
PlatFormCredentialsMatcher platFormCredentialsMatcher = new PlatFormCredentialsMatcher();
platFormCredentialsMatcher.setHashAlgorithmName("MD5");
platFormCredentialsMatcher.setHashIterations(2);
platFormCredentialsMatcher.setStoredCredentialsHexEncoded(true);
return platFormCredentialsMatcher;
}
@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator();
daap.setProxyTargetClass(true);
return daap;
}
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("ShiroRealm") ShiroRealm shiroRealm) {
DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
dwsm.setRealm(shiroRealm);
dwsm.setCacheManager(getEhCacheManager());
return dwsm;
}
@Bean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(@Qualifier("securityManager")DefaultWebSecurityManager dwsm) {
AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
aasa.setSecurityManager(dwsm);
return new AuthorizationAttributeSourceAdvisor();
}
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager dwsm) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
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);
return shiroFilterFactoryBean;
}
/**
* FilterRegistrationBean
* @return
*/
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
filterRegistration.setEnabled(true);
filterRegistration.addUrlPatterns("/*");
filterRegistration.setDispatcherTypes(DispatcherType.REQUEST);
return filterRegistration;
}
}
0

132****1346
3人已关注
领课教育 32518
10316
update 47761
5151
领课教育 18470
husheng 21145
请更新代码 41832
凯哥Java 2422
凯哥Java 2848
凯哥Java 2149