几天前,我从xml配置迁移到Java配置,突然得到Spring安全性不保护任何URL,过滤器根本不工作!
我实现了WebApplicationInitializer
接口来配置Dispatcher servlet,我的配置看起来是这样的:
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.test.project");
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",
new DispatcherServlet(context));
servlet.setLoadOnStartup(1);
servlet.addMapping("/rest/*");
}
安全配置如下所示:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public AutheProvider authProvider() {
return new AuthProvider();
}
@Bean
public AuthenticationFilter authenticationFilter() {
return new AuthenticationFilter();
}
@Bean
public UnauthorizedEntryPoint unauthorizedEntryPoint() {
return new UnauthorizedEntryPoint();
}
@Bean
@Override
public AuthenticationManager authenticationManager() {
ProviderManager providerManager = new ProviderManager(
Arrays.asList(authProvider()));
providerManager.setEraseCredentialsAfterAuthentication(false);
return providerManager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint())
.and()
.addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/rest/**").authenticated();
}
}
我错过了什么?
SecurityConfiguration
课程位于com.test.project
包中。
项目启动后,我可以访问任何URL,authentication
中没有SecurityContext
对象,并且永远不会调用过滤器,neiter mine或Spring Security过滤器。