How to configure Shiro with Spring Boot

后端 未结 2 1106
遇见更好的自我
遇见更好的自我 2021-02-04 19:19

I have a Spring MVC web application that uses Shiro authentication using Spring configuration rather than a shiro.ini.

I want to transition to a Spring Boot application.

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-04 19:31

    Well, it seems that the lack of something, java config like this:

    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.Filter;
    import org.apache.shiro.realm.text.PropertiesRealm;
    import org.apache.shiro.spring.LifecycleBeanPostProcessor;
    import org.apache.shiro.web.filter.authc.AnonymousFilter;
    import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
    import org.apache.shiro.web.filter.authc.LogoutFilter;
    import org.apache.shiro.web.filter.authc.UserFilter;
    import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
    import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
    import org.apache.shiro.web.mgt.WebSecurityManager;
    
    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilter() {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setLoginUrl("/login");
        shiroFilter.setSuccessUrl("/index");
        shiroFilter.setUnauthorizedUrl("/forbidden");
        Map filterChainDefinitionMapping = new HashMap();
        filterChainDefinitionMapping.put("/", "anon");
        filterChainDefinitionMapping.put("/home", "authc,roles[guest]");
        filterChainDefinitionMapping.put("/admin", "authc,roles[admin]");
        shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMapping);
        shiroFilter.setSecurityManager(securityManager());
        Map filters = new HashMap();
        filters.put("anon", new AnonymousFilter());
        filters.put("authc", new FormAuthenticationFilter());
        filters.put("logout", new LogoutFilter());
        filters.put("roles", new RolesAuthorizationFilter());
        filters.put("user", new UserFilter());
        shiroFilter.setFilters(filters);
        System.out.println(shiroFilter.getFilters().size());
        return shiroFilter;
    }
    
    @Bean(name = "securityManager")
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm());
        return securityManager;
    }
    
    @Bean(name = "realm")
    @DependsOn("lifecycleBeanPostProcessor")
    public PropertiesRealm realm() {
        PropertiesRealm propertiesRealm = new PropertiesRealm();
        propertiesRealm.init();
        return propertiesRealm;
    }
    
    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }
    

    https://github.com/lenicliu/eg-spring/tree/master/eg-spring-boot/eg-spring-boot-shiro

提交回复
热议问题