Shiro配置以及redis配置

2018-08-26 17:19:35来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

//druid连接池配置   
@Configuration
public class DruidConfig {
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // 登录查看信息的账号密码.
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        return servletRegistrationBean;
    }
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
@Configuration
@EnableCaching//开启换成配置
public class RedisConfig extends CachingConfigurerSupport {
    private static Logger Logger = LoggerFactory.getLogger(RedisConfig.class);
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.pool.max-wait}")
    private long maxWaitMillis;
    @Bean
    public JedisPool redisPoolFactory() {
        Logger.info("开启redis,redis地址:" + host + ":" + port + ",JedisPool注入成功!!");
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
        return jedisPool;
    }
    /**
     * 配置shiro redisManager 使用的是shiro-redis开源插件
     * 
     * @return
     */
    @Bean
    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host);
        redisManager.setPort(port);
        redisManager.setExpire(1800);// 配置缓存过期时间
        redisManager.setTimeout(timeout);
        return redisManager;
    }
}
@Configuration
public class ShiroConfig {
    /**
     * 缓存和session的管理
     */
    @Autowired
    private ShiroSessionAndCache shiroSessionAndCache;
    
    /**
     * shiro 服务
     */
    @Autowired
    private ShiroService shiroService;
    private static Logger Logger = LoggerFactory.getLogger(ShiroConfig.class);
    @Bean
    public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }
    /**
     * ShiroDialect,为了在thymeleaf里使用shiro的标签的bean
     * @return
     */
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
    /**
     * ShiroFilterFactoryBean 处理拦截资源文件问题。 注意:单独一个ShiroFilterFactoryBean配置是或报错的,因为在
     * 初始化ShiroFilterFactoryBean的时候需要注入:SecurityManager Filter Chain定义说明 
     * 1、一个URL可以配置多个Filter,使用逗号分隔
     * 2、当设置多个过滤器时,全部验证通过,才视为通过 
     * 3、部分过滤器可指定参数,如perms,roles
     */
    @Bean
    public ShiroFilterFactoryBean shirFilter(org.apache.shiro.mgt.SecurityManager securityManager) {
        Logger.info("ShiroConfiguration.shirFilter()");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 如果不设置默认会自动寻找Web工程根目录下的"/login"页面
        shiroFilterFactoryBean.setLoginUrl("/login"); //登录页面
        // 登录成功后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/index");//首页
        // 未授权界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");//错误页面
        // 拦截器.  权限配置
        Map<String, String> filterChainDefinitionMap = shiroService.loadFilterChainDefinitions();
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }
    @Bean
    public org.apache.shiro.mgt.SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置realm.
        securityManager.setRealm(myShiroRealm());
        // 自定义缓存实现 使用redis ,生产环境才需要这么设置,开发环境需要清空全选,所以不建议开启这个
        // securityManager.setCacheManager(cacheManager());
        // 自定义session管理 使用redis
        securityManager.setSessionManager(shiroSessionAndCache.sessionManager());
        return securityManager;
    }
    @Bean
    public ZxShiroRealm myShiroRealm() {
        ZxShiroRealm myShiroRealm = new ZxShiroRealm();
        myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return myShiroRealm;
    }
    /**
     * 凭证匹配器 (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
     *  所以我们需要修改下doGetAuthenticationInfo中的代码; )
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");// 散列算法:这里使用MD5算法;
        hashedCredentialsMatcher.setHashIterations(2);// 散列的次数,比如散列两次,相当于 md5(md5(""));
        return hashedCredentialsMatcher;
    }
    /**
     * 开启shiro aop注解支持. 使用代理方式;所以需要开启代码支持;
     * 
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(org.apache.shiro.mgt.SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
    @Bean
    public RedisSessionDAO redisSessionDAO() {
        return shiroSessionAndCache.redisSessionDAO();
    }
    @Bean
    public DefaultWebSessionManager sessionManager() {
        return shiroSessionAndCache.sessionManager();
    }
    
    /**
     * 注册DelegatingFilterProxy(Shiro)
     * 集成Shiro有2种方法:
     * 1. 按这个方法自己组装一个FilterRegistrationBean(这种方法更为灵活,可以自己定义UrlPattern,
     * 在项目使用中你可能会因为一些很但疼的问题最后采用它, 想使用它你可能需要看官网或者已经很了解Shiro的处理原理了)
     * 2. 直接使用ShiroFilterFactoryBean(这种方法比较简单,其内部对ShiroFilter做了组装工作,无法自己定义UrlPattern,
     * 默认拦截 /*)
     *
     * @param dispatcherServlet
     * @return
     * @create  2016年1月13日
     */
//  @Bean
//  public FilterRegistrationBean filterRegistrationBean() {
//      FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
//      filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
//      //  该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理  
//      filterRegistration.addInitParameter("targetFilterLifecycle", "true");
//      filterRegistration.setEnabled(true);
//      filterRegistration.addUrlPatterns("/*");// 可以自己灵活的定义很多,避免一些根本不需要被Shiro处理的请求被包含进来
//      return filterRegistration;
//  }
}
@Service
public class ShiroService {
    private static Logger Logger = LoggerFactory.getLogger(ShiroService.class);
    @Autowired
    private ResourcesService resourcesService;
    /**
     * 初始化权限
     */
    public Map<String, String> loadFilterChainDefinitions() {
        // 权限控制map.从数据库获取
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        // 配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/assets/**", "anon");
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/img/**", "anon");
        filterChainDefinitionMap.put("/font-awesome/**", "anon");
        // <!-- 过滤链定义,从上向下顺序执行,一般将 /**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
        // <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
        // 自定义加载权限资源关系
        List<Resources> resourcesList = resourcesService.queryAll();
        for (Resources resources : resourcesList) {
            if (StringUtil.isNotEmpty(resources.getResurl())) {
                String permission = "perms[" + resources.getResurl() + "]";
                filterChainDefinitionMap.put(resources.getResurl(), permission);
            }
        }
        filterChainDefinitionMap.put("/**", "authc");
        Logger.info("初始化权限配置成功!");
        return filterChainDefinitionMap;
    }
}
@Component
public class ShiroSessionAndCache {
    @Autowired
    private RedisConfig redisConfig;
    /**
     * RedisSessionDAO shiro sessionDao层的实现 通过redis 使用的是shiro-redis开源插件
     */
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisConfig.redisManager());
        return redisSessionDAO;
    }
    /**
     * shiro session的管理
     */
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); //session的管理,使用redis来处理session
        sessionManager.setSessionDAO(redisSessionDAO());
        return sessionManager;
    }
    /**
     * cacheManager 缓存 redis实现 使用的是shiro-redis开源插件
     * @return
     */
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisConfig.redisManager());
        return redisCacheManager;
    }
}
@Service
public class ShiroPermissionService {
    private static Logger Logger = LoggerFactory.getLogger(ShiroPermissionService.class);
    @Autowired
    private ShiroFilterFactoryBean shiroFilterFactoryBean;
    @Autowired
    private RedisSessionDAO redisSessionDAO;
    @Autowired
    private ShiroService shiroService;
    /**
     * 
     * 此方法描述的是:重新加载权限  刷新缓存
     * 
     * @author: Aarony
     * @version: Nov 13, 2017 10:24:25 AM
     */
    public void updatePermission() {
        synchronized (shiroFilterFactoryBean) {
            AbstractShiroFilter shiroFilter = null;
            try {
                shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
            } catch (Exception e) {
                throw new RuntimeException("get ShiroFilter from shiroFilterFactoryBean error!");
            }
            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
            // 清空老的权限控制
            manager.getFilterChains().clear();
            shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
            shiroFilterFactoryBean.setFilterChainDefinitionMap(shiroService.loadFilterChainDefinitions());
            // 重新构建生成
            Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
            for (Map.Entry<String, String> entry : chains.entrySet()) {
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim().replace(" ", "");
                manager.createChain(url, chainDefinition);
            }
            Logger.info("更新权限成功!");
        }
    }
}

具体的shiro 可以看官网或者这个人的博客:https://blog.csdn.net/LHacker/article/details/10438387 写的蛮详细的。

 

  1. //druid连接池配置
  2.  
    @Configuration
  3.  
    public class DruidConfig {
  4.  
    @Bean
  5.  
    public ServletRegistrationBean druidServlet() {
  6.  
    ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
  7.  
    // 登录查看信息的账号密码.
  8.  
    servletRegistrationBean.addInitParameter("loginUsername", "admin");
  9.  
    servletRegistrationBean.addInitParameter("loginPassword", "123456");
  10.  
    return servletRegistrationBean;
  11.  
    }
  12.  
    @Bean
  13.  
    public FilterRegistrationBean filterRegistrationBean() {
  14.  
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
  15.  
    filterRegistrationBean.setFilter(new WebStatFilter());
  16.  
    filterRegistrationBean.addUrlPatterns("/*");
  17.  
    filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
  18.  
    return filterRegistrationBean;
  19.  
    }
  20.  
    }
  1.  
    @Configuration
  2.  
    @EnableCaching//开启换成配置
  3.  
    public class RedisConfig extends CachingConfigurerSupport {
  4.  
    private static Logger Logger = LoggerFactory.getLogger(RedisConfig.class);
  5.  
    @Value("${spring.redis.host}")
  6.  
    private String host;
  7.  
    @Value("${spring.redis.port}")
  8.  
    private int port;
  9.  
    @Value("${spring.redis.timeout}")
  10.  
    private int timeout;
  11.  
    @Value("${spring.redis.pool.max-idle}")
  12.  
    private int maxIdle;
  13.  
    @Value("${spring.redis.pool.max-wait}")
  14.  
    private long maxWaitMillis;
  15.  
    @Bean
  16.  
    public JedisPool redisPoolFactory() {
  17.  
    Logger.info("开启redis,redis地址:" + host + ":" + port + ",JedisPool注入成功!!");
  18.  
    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
  19.  
    jedisPoolConfig.setMaxIdle(maxIdle);
  20.  
    jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
  21.  
    JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
  22.  
    return jedisPool;
  23.  
    }
  24.  
    /**
  25.  
    * 配置shiro redisManager 使用的是shiro-redis开源插件
  26.  
    *
  27.  
    * @return
  28.  
    */
  29.  
    @Bean
  30.  
    public RedisManager redisManager() {
  31.  
    RedisManager redisManager = new RedisManager();
  32.  
    redisManager.setHost(host);
  33.  
    redisManager.setPort(port);
  34.  
    redisManager.setExpire(1800);// 配置缓存过期时间
  35.  
    redisManager.setTimeout(timeout);
  36.  
    return redisManager;
  37.  
    }
  38.  
    }
  1.  
    @Configuration
  2.  
    public class ShiroConfig {
  3.  
    /**
  4.  
    * 缓存和session的管理
  5.  
    */
  6.  
    @Autowired
  7.  
    private ShiroSessionAndCache shiroSessionAndCache;
  8.  
     
  9.  
    /**
  10.  
    * shiro 服务
  11.  
    */
  12.  
    @Autowired
  13.  
    private ShiroService shiroService;
  14.  
    private static Logger Logger = LoggerFactory.getLogger(ShiroConfig.class);
  15.  
    @Bean
  16.  
    public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
  17.  
    return new LifecycleBeanPostProcessor();
  18.  
    }
  19.  
    /**
  20.  
    * ShiroDialect,为了在thymeleaf里使用shiro的标签的bean
  21.  
    * @return
  22.  
    */
  23.  
    @Bean
  24.  
    public ShiroDialect shiroDialect() {
  25.  
    return new ShiroDialect();
  26.  
    }
  27.  
    /**
  28.  
    * ShiroFilterFactoryBean 处理拦截资源文件问题。 注意:单独一个ShiroFilterFactoryBean配置是或报错的,因为在
  29.  
    * 初始化ShiroFilterFactoryBean的时候需要注入:SecurityManager Filter Chain定义说明
  30.  
    * 1、一个URL可以配置多个Filter,使用逗号分隔
  31.  
    * 2、当设置多个过滤器时,全部验证通过,才视为通过
  32.  
    * 3、部分过滤器可指定参数,如perms,roles
  33.  
    */
  34.  
    @Bean
  35.  
    public ShiroFilterFactoryBean shirFilter(org.apache.shiro.mgt.SecurityManager securityManager) {
  36.  
    Logger.info("ShiroConfiguration.shirFilter()");
  37.  
    ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
  38.  
    // 必须设置 SecurityManager
  39.  
    shiroFilterFactoryBean.setSecurityManager(securityManager);
  40.  
    // 如果不设置默认会自动寻找Web工程根目录下的"/login"页面
  41.  
    shiroFilterFactoryBean.setLoginUrl("/login"); //登录页面
  42.  
    // 登录成功后要跳转的链接
  43.  
    shiroFilterFactoryBean.setSuccessUrl("/index");//首页
  44.  
    // 未授权界面;
  45.  
    shiroFilterFactoryBean.setUnauthorizedUrl("/403");//错误页面
  46.  
    // 拦截器. 权限配置
  47.  
    Map<String, String> filterChainDefinitionMap = shiroService.loadFilterChainDefinitions();
  48.  
    shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
  49.  
    return shiroFilterFactoryBean;
  50.  
    }
  51.  
    @Bean
  52.  
    public org.apache.shiro.mgt.SecurityManager securityManager() {
  53.  
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
  54.  
    // 设置realm.
  55.  
    securityManager.setRealm(myShiroRealm());
  56.  
    // 自定义缓存实现 使用redis ,生产环境才需要这么设置,开发环境需要清空全选,所以不建议开启这个
  57.  
    // securityManager.setCacheManager(cacheManager());
  58.  
    // 自定义session管理 使用redis
  59.  
    securityManager.setSessionManager(shiroSessionAndCache.sessionManager());
  60.  
    return securityManager;
  61.  
    }
  62.  
    @Bean
  63.  
    public ZxShiroRealm myShiroRealm() {
  64.  
    ZxShiroRealm myShiroRealm = new ZxShiroRealm();
  65.  
    myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
  66.  
    return myShiroRealm;
  67.  
    }
  68.  
    /**
  69.  
    * 凭证匹配器 (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
  70.  
    * 所以我们需要修改下doGetAuthenticationInfo中的代码; )
  71.  
    * @return
  72.  
    */
  73.  
    @Bean
  74.  
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
  75.  
    HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
  76.  
    hashedCredentialsMatcher.setHashAlgorithmName("md5");// 散列算法:这里使用MD5算法;
  77.  
    hashedCredentialsMatcher.setHashIterations(2);// 散列的次数,比如散列两次,相当于 md5(md5(""));
  78.  
    return hashedCredentialsMatcher;
  79.  
    }
  80.  
    /**
  81.  
    * 开启shiro aop注解支持. 使用代理方式;所以需要开启代码支持;
  82.  
    *
  83.  
    * @param securityManager
  84.  
    * @return
  85.  
    */
  86.  
    @Bean
  87.  
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(org.apache.shiro.mgt.SecurityManager securityManager) {
  88.  
    AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
  89.  
    authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
  90.  
    return authorizationAttributeSourceAdvisor;
  91.  
    }
  92.  
    @Bean
  93.  
    public RedisSessionDAO redisSessionDAO() {
  94.  
    return shiroSessionAndCache.redisSessionDAO();
  95.  
    }
  96.  
    @Bean
  97.  
    public DefaultWebSessionManager sessionManager() {
  98.  
    return shiroSessionAndCache.sessionManager();
  99.  
    }
  100.  
     
  101.  
    /**
  102.  
    * 注册DelegatingFilterProxy(Shiro)
  103.  
    * 集成Shiro有2种方法:
  104.  
    * 1. 按这个方法自己组装一个FilterRegistrationBean(这种方法更为灵活,可以自己定义UrlPattern,
  105.  
    * 在项目使用中你可能会因为一些很但疼的问题最后采用它, 想使用它你可能需要看官网或者已经很了解Shiro的处理原理了)
  106.  
    * 2. 直接使用ShiroFilterFactoryBean(这种方法比较简单,其内部对ShiroFilter做了组装工作,无法自己定义UrlPattern,
  107.  
    * 默认拦截 /*)
  108.  
    *
  109.  
    * @param dispatcherServlet
  110.  
    * @return
  111.  
    * @create 2016年1月13日
  112.  
    */
  113.  
    // @Bean
  114.  
    // public FilterRegistrationBean filterRegistrationBean() {
  115.  
    // FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
  116.  
    // filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
  117.  
    // // 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理
  118.  
    // filterRegistration.addInitParameter("targetFilterLifecycle", "true");
  119.  
    // filterRegistration.setEnabled(true);
  120.  
    // filterRegistration.addUrlPatterns("/*");// 可以自己灵活的定义很多,避免一些根本不需要被Shiro处理的请求被包含进来
  121.  
    // return filterRegistration;
  122.  
    // }
  123.  
    }
  1.  
    @Service
  2.  
    public class ShiroService {
  3.  
    private static Logger Logger = LoggerFactory.getLogger(ShiroService.class);
  4.  
    @Autowired
  5.  
    private ResourcesService resourcesService;
  6.  
    /**
  7.  
    * 初始化权限
  8.  
    */
  9.  
    public Map<String, String> loadFilterChainDefinitions() {
  10.  
    // 权限控制map.从数据库获取
  11.  
    Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
  12.  
    // 配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
  13.  
    filterChainDefinitionMap.put("/logout", "logout");
  14.  
    filterChainDefinitionMap.put("/assets/**", "anon");
  15.  
    filterChainDefinitionMap.put("/css/**", "anon");
  16.  
    filterChainDefinitionMap.put("/js/**", "anon");
  17.  
    filterChainDefinitionMap.put("/img/**", "anon");
  18.  
    filterChainDefinitionMap.put("/font-awesome/**", "anon");
  19.  
    // <!-- 过滤链定义,从上向下顺序执行,一般将 /**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
  20.  
    // <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
  21.  
    // 自定义加载权限资源关系
  22.  
    List<Resources> resourcesList = resourcesService.queryAll();
  23.  
    for (Resources resources : resourcesList) {
  24.  
    if (StringUtil.isNotEmpty(resources.getResurl())) {
  25.  
    String permission = "perms[" + resources.getResurl() + "]";
  26.  
    filterChainDefinitionMap.put(resources.getResurl(), permission);
  27.  
    }
  28.  
    }
  29.  
    filterChainDefinitionMap.put("/**", "authc");
  30.  
    Logger.info("初始化权限配置成功!");
  31.  
    return filterChainDefinitionMap;
  32.  
    }
  33.  
    }
  1.  
    @Component
  2.  
    public class ShiroSessionAndCache {
  3.  
    @Autowired
  4.  
    private RedisConfig redisConfig;
  5.  
    /**
  6.  
    * RedisSessionDAO shiro sessionDao层的实现 通过redis 使用的是shiro-redis开源插件
  7.  
    */
  8.  
    public RedisSessionDAO redisSessionDAO() {
  9.  
    RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
  10.  
    redisSessionDAO.setRedisManager(redisConfig.redisManager());
  11.  
    return redisSessionDAO;
  12.  
    }
  13.  
    /**
  14.  
    * shiro session的管理
  15.  
    */
  16.  
    public DefaultWebSessionManager sessionManager() {
  17.  
    DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); //session的管理,使用redis来处理session
  18.  
    sessionManager.setSessionDAO(redisSessionDAO());
  19.  
    return sessionManager;
  20.  
    }
  21.  
    /**
  22.  
    * cacheManager 缓存 redis实现 使用的是shiro-redis开源插件
  23.  
    * @return
  24.  
    */
  25.  
    public RedisCacheManager cacheManager() {
  26.  
    RedisCacheManager redisCacheManager = new RedisCacheManager();
  27.  
    redisCacheManager.setRedisManager(redisConfig.redisManager());
  28.  
    return redisCacheManager;
  29.  
    }
  30.  
    }
  1.  
    @Service
  2.  
    public class ShiroPermissionService {
  3.  
    private static Logger Logger = LoggerFactory.getLogger(ShiroPermissionService.class);
  4.  
    @Autowired
  5.  
    private ShiroFilterFactoryBean shiroFilterFactoryBean;
  6.  
    @Autowired
  7.  
    private RedisSessionDAO redisSessionDAO;
  8.  
    @Autowired
  9.  
    private ShiroService shiroService;
  10.  
    /**
  11.  
    *
  12.  
    * 此方法描述的是:重新加载权限 刷新缓存
  13.  
    *
  14.  
    * @author: Aarony
  15.  
    * @version: Nov 13, 2017 10:24:25 AM
  16.  
    */
  17.  
    public void updatePermission() {
  18.  
    synchronized (shiroFilterFactoryBean) {
  19.  
    AbstractShiroFilter shiroFilter = null;
  20.  
    try {
  21.  
    shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();
  22.  
    } catch (Exception e) {
  23.  
    throw new RuntimeException("get ShiroFilter from shiroFilterFactoryBean error!");
  24.  
    }
  25.  
    PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
  26.  
    DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
  27.  
    // 清空老的权限控制
  28.  
    manager.getFilterChains().clear();
  29.  
    shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();
  30.  
    shiroFilterFactoryBean.setFilterChainDefinitionMap(shiroService.loadFilterChainDefinitions());
  31.  
    // 重新构建生成
  32.  
    Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();
  33.  
    for (Map.Entry<String, String> entry : chains.entrySet()) {
  34.  
    String url = entry.getKey();
  35.  
    String chainDefinition = entry.getValue().trim().replace(" ", "");
  36.  
    manager.createChain(url, chainDefinition);
  37.  
    }
  38.  
    Logger.info("更新权限成功!");
  39.  
    }
  40.  
    }
  41.  
    }

具体的shiro 可以看官网或者这个人的博客:https://blog.csdn.net/LHacker/article/details/10438387 写的蛮详细的。

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:开始食用grpc(之一)

下一篇:maven-生命周期与插件