thymeleaf+Sitemesh+Shiro踩坑

接上一篇springboot2整合thymeleaf和Sitemesh

如果我們在sitemesh的裝飾頁面中使用shiro標籤的話,會報

No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton.  This is an invalid application configuration.

這是原因是由於sitemesh不在shiro securityManager的管理中的原因,爲什麼沒在呢,還是因爲shiro的Filter沒有控制住sitemesh的FORWARD

這怎麼辦呢,那就給shiroFilter加上

 @Bean
    public FilterRegistrationBean delegatingFilterProxy(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        DelegatingFilterProxy proxy = new DelegatingFilterProxy();
        proxy.setTargetFilterLifecycle(true);
        proxy.setTargetBeanName("shiroFilter");
        filterRegistrationBean.setEnabled(true);
        filterRegistrationBean.setFilter(proxy);
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setAsyncSupported(true);
        EnumSet<DispatcherType> types = EnumSet.of(DispatcherType.REQUEST,DispatcherType.FORWARD);
        filterRegistrationBean.setDispatcherTypes(types);
        return filterRegistrationBean;
    }

我這個是在ShiroConfig中配置的,並且需要配置ShiroFilterFactoryBean的@Bean的名字爲shiroFilter對應上面配置的shiroFilter

這樣spring就可以管理你的shiro了,再配置FilterRegistrationBean#setDispatcherTypes爲DispatcherType.REQUEST,DispatcherType.FORWARD這樣就齊活了,這個是2.x後改了,1.5.x版本的默認有FORWARD

@Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauth");
        // Shiro連接約束配置,即過濾鏈的定義
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/favicon.ico**", "anon");
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/error", "anon");
        // 退出 logout地址,shiro去清除session
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/**", "user");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章