好久不用Spring MVC了,折腾了好久,总算是完成了,记录一下。
Spring
版本是5.3.29
,Shiro 1.12.0
。
pom.xml
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.12.0</version> </dependency>
程序初始化器:
@Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] {AppConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { WebConfig.class }; } @Override public void onStartup(ServletContext servletContext) throws ServletException { FilterRegistration.Dynamic shiroFilter = servletContext.addFilter("shiroFilterFactoryBean", DelegatingFilterProxy.class); shiroFilter.setInitParameter("targetFilterLifecycle", "true"); shiroFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*"); super.onStartup(servletContext); }
ShiroConfig:
@Configuration @PropertySource("classpath:shiro.properties") @ComponentScan(basePackages = { "com.store.security" }) @Import({ ShiroBeanConfiguration.class, ShiroWebConfiguration.class, ShiroWebFilterConfiguration.class }) public class ShiroConfig { // 定义主要的Filter @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager sm) { ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); bean.setSecurityManager(sm); bean.setLoginUrl("/admin/login"); bean.setUnauthorizedUrl("/login"); bean.setSuccessUrl("/"); Map<String, String> map = new HashMap<>(); map.put("/", "anon"); map.put("/admin/login", "anon"); map.put("/admin", "authc"); map.put("/admin/*", "authc"); bean.setFilterChainDefinitionMap(map); return bean; } ... }
Shiro
之前版本有遍历路径漏洞,所以Shiro
提供了一个ShiroRequestMappingConfig
配置类,我们在这里暂不引入,在WebConfig中再引入,因为它依赖一个RequestMappingHandlerMapping
bean,只有启用@EnableWebMvc注解才会注入,所以我们把这个配置放到那里引入。