使用java配置的Spring安全性不保护URL

时间:2018-01-24 15:59:39

标签: java spring spring-mvc spring-security

几天前,我从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过滤器。

0 个答案:

没有答案