Spring Security AuthenticationServiceException преобразуется в НедостаточноAuthenticationException - PullRequest
0 голосов
/ 05 марта 2019

У меня проблема с обработкой исключений во время аутентификации с использованием Spring Security.

Это мой AuthenticationProvider, где при каждом исключении выбрасывается AuthenticationServiceException.

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        try {
            // ...
        } catch (Exception e) {
            throw new AuthenticationServiceException(e.getMessage(), e);
        }
    }
}

Нижемой пользовательский AuthenticationProvider.

@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.debug(e.toString());
    }
}

Это конфигурация безопасности

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationProvider authenticationProvider;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .authenticationProvider(authenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
            .and()
                .httpBasic()
            .and()
                .csrf().disable()
            .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint);
    }
}

Все срабатывает, как и ожидалось.Проблема в том, что в AuthenticationProvider AuthenticationException является экземпляром InsufficientAuthenticationException, а не AuthenticationServiceException, как выброшено AuthenticationProvider.Вместо этого в MyAuthenticationEntryPoint я хочу получить исключение с указанием причины, которое является пользовательским исключением.

Как я могу решить эту проблему?Почему Spring заменяет AuthenticationServiceException на InsufficientAuthenticationException?

Заранее спасибо.

РЕШЕНИЕ

Я нашел решение!Проблема в SecurityConfig классе..authenticationEntryPoint(authenticationEntryPoint) должно быть меньше .httpBasic() и не задано глобально.

Правильная конфигурация следующая:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
        .and()
            .httpBasic()
                .authenticationEntryPoint(authenticationEntryPoint)
        .and()
            .csrf().disable();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...