Spring (boot) Предварительная аутентификация безопасности с разрешенными ресурсами, все еще аутентифицированными

Я использую Spring Boot 1.5.6 (также пробовал с 1.5.4). Я использую

RequestHeaderAuthenticationFilter 

и

PreAuthenticatedAuthenticationProvider 

чтобы защитить мое весеннее веб-приложение mvc, а также разрешить доступ к пути контроллера и статическим ресурсам.

В моем

RequestHeaderAuthenticationFilter

настроить я хочу

setExceptionIfHeaderMissing(true);

так что я знаю, если переменная заголовка была отправлена ​​в запросе.

Когда я пытаюсь получить доступ к любому из разрешенных ресурсов, Spring Security всегда ищет переменную заголовка в запросе и выдает

PreAuthenticatedCredentialsNotFoundException

Почему Spring Security все еще пытается найти предварительно аутентифицированный принципал, хотя я пытаюсь получить доступ к разрешенному (незащищенному) ресурсу? Как я могу обойти это поведение?

Моя конфигурация Java для WebSecurityConfigurerAdapter находится ниже

@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 ответ

Решение

У меня была та же проблема, и оказалось, что это связано с тем, что помимо регистрации в SecurityFilterChain, Spring Boot также регистрировал RequestHeaderAuthenticationFilter в контексте сервлета. Решение состоит в том, чтобы использовать FilterRegistrationBean чтобы Boot не мог автоматически зарегистрировать фильтр в контексте сервлета.

Более подробная информация здесь: Сценарий PreAuthenticated Spring Boot Security с анонимным доступом

Другие вопросы по тегам