shiro 基于角色粗粒度与URL细粒度权限控制实现

时间:2021-12-16 18:59:50

shiro 注解方式的权限控制基于代理实现,

  如果写了用了多个注解会按照内定的顺序一个一个验证, 而不是按使用的先后顺序.

  RequiresRoles
  RequiresPermissions
  RequiresAuthentication
  RequiresUser
  RequiresGuest

 

 

  @Bean
  @DependsOn({"lifecycleBeanPostProcessor"})
  public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
   DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
   advisorAutoProxyCreator.setProxyTargetClass(true);
   return advisorAutoProxyCreator;
  }

        //权限控制map
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();

     //filterChainDefinitionMap.put("/user/**", "roles[user]");
filterChainDefinitionMap.put("/user/**", "perms[user]");
filterChainDefinitionMap.put("/account/**", "perms[account]");

    
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Set<String> set = new HashSet<String>();
     //set.add("users");
     //info.setRoles(set);
set.add("user");
info.setStringPermissions(set);

return info;


 

url基于过滤器实现:

  //自定义过滤器
  Map<String, Filter> filterMap = new LinkedHashMap<>();
  shiroFilterFactoryBean.setFilters(filterMap);

  filterChainDefinitionMap.put("/user/**", "authc");
  filterChainDefinitionMap.put("/**", "authc");
  filterChainDefinitionMap.put("/user/**", "requestURL"); //必须在/**,authc之前添加被控制的路径

    @Autowired
IPermissionService permissionService;

public static URLPathMatchingFilter testUtils;

   // @Autowired 注入失败 使用此方式 @PostConstruct
@PostConstruct
public void init() {
testUtils = this;
}

  
  //保存当前地址并重定向到登录界面  参考张开涛大神的<跟我学shiro>
  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse resp = (HttpServletResponse) response;
  saveRequestAndRedirectToLogin(req, resp);
  return false;


 

 项目源码地址 (问题多多,请不吝赐教)