Spring Security AuthenticationServiceException转换为InsufficientAuthenticationException

时间:2019-03-05 09:18:13

标签: spring exception spring-security

我在使用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中,AuthenticationExceptionInsufficientAuthenticationException的实例,而不是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();
}

0 个答案:

没有答案