Spring Security 4.x JavaConfig для базовой аутентификации с Hawtio

Я пытаюсь подключить Hawtio (1.4.64) к агенту Jolokia (1.3.3), работающему в приложении Spring в Tomcat 7.

После недавнего обновления до Spring Security (4.0.3) hawtio прекратил аутентификацию должным образом (используя базовую аутентификацию), и мы были возвращены на страницу входа, аналогичную проблеме № 1975. В отличие от этого вопроса, мы используем только агент Jolokia, а не включаем hawtio в наше приложение (и мы не используем Spring Boot).

После изучения журналов отладки Spring создается впечатление, что AnonymousAuthenticationFilter устанавливает пользователя как "анонимного" до применения BasicAuthenticationFilter. Поэтому я настроил конфигурацию безопасности и отключил все настройки по умолчанию, оставив следующее:

@Configuration
@Order(2)
public static class JolokiaSecurityConfig extends WebSecurityConfigurerAdapter {

    public JolokiaSecurityConfig() {
        super(true); // disable defaults
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .requestMatchers().antMatchers("/jolokia/**")
            .and().authorizeRequests().antMatchers("/jolokia/**").hasAuthority(BaseRoles.DEVELOPER).and().httpBasic();
    }
}

Теперь, когда я вхожу в Hawtio, я получаю сообщение об ошибке в консоли Hawtio, которое включает некоторые выходные данные с моего сервера Tomcat7: HTTP Status 500 - Объект аутентификации не найден в SecurityContext

Трассировки стека:

Jul 06, 2016 12:43:14 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jolokia-agent] in context with path [/foobar] threw exception
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:378)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:222)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:123)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)

...

Есть идеи, почему базовая аутентификация больше не работает? Спасибо за любую помощь!

1 ответ

Решение

Мы обошли проблему, переопределив обработку исключений, чтобы снова вызвать BasicAuthenticationEntryPoint:

@Configuration
@Order(2)
public static class JolokiaSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String REALM = "our admin services";
    private static final String JOLOKIA_URL_PATTERN = "/jolokia/**";

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        BasicAuthenticationEntryPoint authenticationEntryPoint = new BasicAuthenticationEntryPoint();
        authenticationEntryPoint.setRealmName(REALM);
        http
            .csrf().disable()
            .requestMatchers().antMatchers(JOLOKIA_URL_PATTERN)
            .and().authorizeRequests().antMatchers(JOLOKIA_URL_PATTERN).hasAuthority(BaseRoles.DEVELOPER)
            .and().httpBasic().realmName(REALM)
            .and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
    }
}
Другие вопросы по тегам