Spring(启动)安全预身份验证,允许的资源仍然经过身份验证

时间:2017-08-31 00:07:04

标签: spring spring-mvc spring-boot spring-security

我正在使用Spring Boot 1.5.6(也尝试过1.5.4)。 我正在使用

RequestHeaderAuthenticationFilter 

PreAuthenticatedAuthenticationProvider 

保护我的spring mvc web应用程序,并允许访问控制器路径和静态资源。

在我的

RequestHeaderAuthenticationFilter

设置我想要

setExceptionIfHeaderMissing(true);

以便我知道是否已在请求中发送了标头变量。

当我尝试访问任何允许的资源时,Spring Security始终在请求中查找标头变量并抛出

PreAuthenticatedCredentialsNotFoundException

为什么即使我尝试访问允许的(未受保护的)资源,Spring安全仍然会尝试查找预先验证的主体? 我怎样才能规避这种行为?

我的WebSecurityConfigurerAdapter的java配置在

之下
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{


private static final Logger log = LoggerFactory.getLogger(SecurityConfig.class);


@Autowired
protected UserDetailsService userDetailsService; 



@Bean
public PreAuthenticatedAuthenticationProvider preAuthenticatedAuthenticationProvider(){

    log.info("Configuring pre authentication provider");

    UserDetailsByNameServiceWrapper<PreAuthenticatedAuthenticationToken> wrapper = 
            new UserDetailsByNameServiceWrapper<PreAuthenticatedAuthenticationToken>(
                    userDetailsService);

    PreAuthenticatedAuthenticationProvider it = new PreAuthenticatedAuthenticationProvider();
    it.setPreAuthenticatedUserDetailsService(wrapper);

    return it;      
} 

@Bean
public RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter() throws Exception{

    RequestHeaderAuthenticationFilter it = new RequestHeaderAuthenticationFilter();
    it.setAuthenticationManager(authenticationManager());
    it.setExceptionIfHeaderMissing(true);
    return it;
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    log.info("configure authentication provider");
    auth.authenticationProvider(preAuthenticatedAuthenticationProvider());

}


@Override
protected void configure(HttpSecurity http) throws Exception {
    log.info("Configure HttpSecurity");
    http
        .authorizeRequests()
            .antMatchers("/permitted/**", "/css/**", "/js/**", "/images/**", "/webjars/**")
                .permitAll()
            .anyRequest()
                    .authenticated()
            .and().addFilter(requestHeaderAuthenticationFilter())

    ;
}    


 @Override
 public void configure(WebSecurity web) throws Exception {
     web
        .ignoring()
            .antMatchers("/permitted/**", "/css/**", "/js/**", "/images/**", "/webjars/**"); 
}   
}

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,事实证明这与以下事实有关:除了在SecurityFilterChain中注册外,Spring Boot还在使用Servlet Context注册RequestHeaderAuthenticationFilter。解决方案是使用FilterRegistrationBean来阻止Boot使用Servlet Context自动注册过滤器。

此处有更多详情: Spring Boot Security PreAuthenticated Scenario with Anonymous access