shiro 从数据库中获取url 配置权限

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35167373/article/details/81085148

目标:这种配置是写死的,而我们需要做活

1、使用 perms 如:

      /admins/user/**=perms[user:add:*]表示:要访问【/admins/user/**】必须具有【user:add:* 】权限

      perms支持使用逗号隔开,不过需要两个权限都有才可以

2、原配置类为  ShiroFilterFactoryBean

 <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">

3、重写 ShiroFilterFactoryBean 的  setFilterChainDefinitions 方法 ,同时将上面的shiroFilter中的class修改为新建的类

package com.sub.shiro;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.config.Ini;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;
import com.sub.model.RoleandpowerView;
import com.sub.service.EmployeeService;



public class ShiroPermissionFactory extends ShiroFilterFactoryBean{
	
	/**xml中的配置*/
	public static String definitions;
	
	@Resource(name = "EmployeeServiceImpl")
	private EmployeeService employeeService;


	@Override
	public void setFilterChainDefinitions(String definitions) {
		ShiroPermissionFactory.definitions = definitions;
		
		List<RoleandpowerView> list = employeeService.getPowerListAll();
		Map<String, String> otherChains = new HashMap<String,String>();
        for(RoleandpowerView ro : list){
          otherChains.put("/"+ro.getUrl(), "perms["+ro.getSp_power_id()+"]");
        }
		        
		//从配置文件加载权限配置
		Ini ini = new Ini();
        ini.load(definitions);
        Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
        if (CollectionUtils.isEmpty(section)) {
            section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        }
        
        //加入权限集合
        section.putAll(otherChains);
        section.put("/**", "authc");
        setFilterChainDefinitionMap(section);
	}
}

4、给用户分配权限,重写AuthorizingRealm(登录验证的类)中的 doGetAuthorizationInfo方法,此方法访问需要验证的url时触发,如果配置了缓存则只是第一次触发

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {		
		List<RoleandpowerView> list = employeeService.getPowerList();
		Set<String> prems = new HashSet<String>();
		for(RoleandpowerView i : list){
			if(i.getIshave()!=0 && i.getLevel()!=0)
			prems.add(String.valueOf(i.getSp_power_id()));
		}	
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(prems);
		return info;
	}

猜你喜欢

转载自blog.csdn.net/qq_35167373/article/details/81085148