【问题标题】:How can I intercept and log errors that occur when hitting the TokenEndpoint?如何拦截和记录命中 TokenEndpoint 时发生的错误?
【发布时间】:2018-08-21 05:53:45
【问题描述】:
【问题讨论】:
标签:
spring
logging
spring-security
oauth-2.0
spring-security-oauth2
【解决方案1】:
我们可以使用在WebMvcConfigurationSupport 中定义的覆盖HandlerExceptionResolverComposite 异常处理程序。这会将所有异常解析器组合成一个异常解析器。然后我们可以定义您自己的异常解析器。
我们可以使用的异常解析器之一是ExceptionHandlerExceptionResolver,这将通过涉及带有@ControllerAdvice 注释的类来启用基于AOP 的异常处理。
在我们的自定义控制器建议中,我们可以对不同的异常使用处理程序:
@ExceptionHandler({OAuth2Exception.class})
public ResponseEntity<Object> handleOAuth2Exception(final OAuth2Exception exception, final WebRequest request) {
LOGGER.debug("OAuth failed on request processing", exception);
【解决方案2】:
我们最终解决这个问题的方法是使用spring-aop。我们只是截取了正确的位置并在其中记录了一条错误消息:
@Slf4j
@Aspect
@Component
public class OAuthErrorLoggingAspect {
private static final String ERROR_MESSAGE = "Error during token generation: ";
@Before("execution("
+ "public * "
+ "org.springframework.security.oauth2.provider.endpoint"
+ ".TokenEndpoint.handleException(Exception)) && args(ex))")
public void handleExceptionLogging(Exception ex) {
if (ex instanceof ClientAbortException) {
log.debug(ERROR_MESSAGE, ex);
} else {
log.error(ERROR_MESSAGE, ex);
}
}
@Before("execution("
+ "public * "
+ "org.springframework.security.oauth2.provider.endpoint"
+ ".TokenEndpoint.handleHttpRequestMethodNotSupportedException("
+ "org.springframework.web.HttpRequestMethodNotSupportedException)) && args(ex))")
public void handleHttpRequestMethodNotSupportedLogging(HttpRequestMethodNotSupportedException ex) {
log.debug(ERROR_MESSAGE, ex);
}
@Before("execution("
+ "public * "
+ "org.springframework.security.oauth2.provider.endpoint"
+ ".TokenEndpoint.handleClientRegistrationException("
+ "Exception)) && args(ex))")
public void handleClientRegistrationErrorLogging(Exception ex) {
log.debug(ERROR_MESSAGE, ex);
}
@Before("execution("
+ "public * "
+ "org.springframework.security.oauth2.provider.endpoint"
+ ".TokenEndpoint.handleException("
+ "org.springframework.security.oauth2.common.exceptions.OAuth2Exception)) && args(ex))")
public void handleOAuth2ExceptionLogging(OAuth2Exception ex) {
log.debug(ERROR_MESSAGE, ex);
}
}