转载自:http://www.kssfeng.com/content/98ba790618b211e9a181525400cc6d13
为什么添加or关系处理器
shiro中配置roles的时候当存在多个角色参数时,这是各参数的关系是and关系。
如:roles[admin,user],这样配置的时候需要同时是admin和user角色是才能通过。
shiro默认不能处理admin或user这种情况,当需要时候or关系时需要配置一个自定义的filter
添加RoleOrFilter类继承AuthorizationFilter
public class RoleOrFilter extends AuthorizationFilter {
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
Subject subject = getSubject(request,response);
String[] roles = (String[])mappedValue;
if(roles == null || roles.length ==0){
return true;
}
for(String role:roles){
if(subject.hasRole(role)){
return true;
}
}
return false;
}
}
在shiro中配置过滤器
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, Filter> filtersMap = new LinkedHashMap<>();
filtersMap.put("roleOrFilter",new RoleOrFilter());//可以配置RoleOrFilter的Bean
//自定义拦截器限制并发人数
//限制同一帐号同时在线的个数
// filtersMap.put("kickout", kickoutSessionControlFilter());
shiroFilterFactoryBean.setFilters(filtersMap);
shiroFilterFactoryBean.setLoginUrl("/login");
// shiroFilterFactoryBean.setSuccessUrl("/login");
Map<String ,String> filterChainDefinitionMap = new LinkedHashMap<>();
// filterChainDefinitionMap.put("/guest/**","anon");
filterChainDefinitionMap.put("/wechart/start","roles[admin]");
filterChainDefinitionMap.put("/article/getArticleInfo","anon");
filterChainDefinitionMap.put("/article/getArticleContent","anon");
// filterChainDefinitionMap.put("/article/save","anon");
filterChainDefinitionMap.put("/article/save","roleOrFilter[admin,user]");
filterChainDefinitionMap.put("/ueditor/**","anon");
filterChainDefinitionMap.put("/myboke/**","anon");
filterChainDefinitionMap.put("/classInfo/**","anon");
filterChainDefinitionMap.put("/login","anon");
// filterChainDefinitionMap.put("/login","anon");
filterChainDefinitionMap.put("/**","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
这样就可以通过类似roleOrFilter[admin,user]来使用或关系进行角色控制了