如何捕获和处理InvalidGrantException(已禁用用户)?

时间:2018-09-15 09:26:31

标签: spring-boot spring-security spring-security-oauth2

我注意到ResponseEntityExceptionHandler不能与Spring Security在Spring Boot应用程序中引发的异常一起使用。

但是,我需要一种捕获InvalidGrantException的方法,当用户帐户仍然被禁用时,该方法似乎会被抛出。

用例很简单:如果当前禁用了某个用户,我想向客户端抛出一个适当的错误。它可以相应地显示一条消息。

现在,Spring Security的响应是

{
  error: "invalid_grant", 
  error_description: "User is disabled"
}

我看到了this question,但是由于某种原因,我的AuthFailureHandler没有被调用:

@Configuration
@EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {

    @Component
    public class AuthFailureHandler implements AuthenticationEntryPoint {

        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

            // Never reached ..
            System.out.println("Hello World!");
        }
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling()                        
            .authenticationEntryPoint(customAuthEntryPoint());;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint(customAuthEntryPoint());
    }

    @Bean
    public AuthenticationEntryPoint customAuthEntryPoint(){
        return new AuthFailureHandler();
    }

}

知道我缺少什么吗?

2 个答案:

答案 0 :(得分:0)

创建一个扩展了ResponseEntityExceptionHandler的自定义类,并用@ControllerAdvice对其进行注释并处理OAuth2ExceptionInvalidGrantException的基类)。

@ExceptionHandler({OAuth2Exception.class})
public ResponseEntity<Object> handleOAuth2Exception(OAuth2Exception exception, WebRequest request) {
    LOGGER.debug("OAuth failed on request processing", exception);
    return this.handleExceptionInternal(exception, ErrorOutputDto.create(exception.getOAuth2ErrorCode(), exception.getMessage()), new HttpHeaders(), HttpStatus.valueOf(exception.getHttpErrorCode()), request);
}

使用HandlerExceptionResolverComposite将系统中的所有异常解析器组合为一个异常解析器。这将覆盖在中定义的相应bean WebMvcConfigurationSupport类。添加exceptionResolvers的列表,例如DefaultErrorAttributesExceptionHandlerExceptionResolver(这可以通过涉及带有@ControllerAdvice批注的类(例如我们创建的扩展{{3 }}。

<bean id="handlerExceptionResolver" class="org.springframework.web.servlet.handler.HandlerExceptionResolverComposite">
<property name="exceptionResolvers">
    <list>
        <bean class="org.springframework.boot.web.servlet.error.DefaultErrorAttributes"/>

        <bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver">
            <property name="messageConverters">
                <list>
                    <ref bean="jackson2HttpMessageConverter" />
                </list>
            </property>
        </bean>
    </list>
</property>

答案 1 :(得分:0)

您是否尝试过定义@ControllerAdvice的{​​{1}}的作品吗?

InvalidGrantException