如何在TokenEndPoint Spring oAuth2中注入WebResponseExceptionTranslator

时间:2015-10-02 17:15:37

标签: java spring spring-security oauth-2.0 spring-security-oauth2

我正在尝试自定义Spring Security oAuth TokenEndpoint类处理异常的方式。我想返回一个比DefaultWebResponseExceptionTranslator当前更自定义的JSON响应。我无法弄清楚如何通过XML注入自定义转换器。这是我的代码片段:

弹簧security.xml文件

<oauth:authorization-server
    client-details-service-ref="clientDetails" token-services-ref="tokenServices" 
    user-approval-handler-ref="userApprovalHandler" request-validator-ref="requestValidator" >
    <oauth:client-credentials />
    <oauth:password />
</oauth:authorization-server>

这是AbstractServerBeanDefinitionParser

的相关代码部分
    BeanDefinitionBuilder tokenEndpointBean = BeanDefinitionBuilder.rootBeanDefinition(TokenEndpoint.class);
    tokenEndpointBean.addPropertyReference("clientDetailsService", clientDetailsRef);
    tokenEndpointBean.addPropertyReference("tokenGranter", tokenGranterRef);
    authorizationEndpointBean.addPropertyReference("oAuth2RequestValidator", oAuth2RequestValidatorRef);
    parserContext.getRegistry()
            .registerBeanDefinition("oauth2TokenEndpoint", tokenEndpointBean.getBeanDefinition());
    if (StringUtils.hasText(oAuth2RequestFactoryRef)) {
        tokenEndpointBean.addPropertyReference("oAuth2RequestFactory", oAuth2RequestFactoryRef);
    }
    if (StringUtils.hasText(oAuth2RequestValidatorRef)) {
        tokenEndpointBean.addPropertyReference("oAuth2RequestValidator", oAuth2RequestValidatorRef);
    }

TokenEndpoint扩展了AbstractEndpoint,它是定义翻译器的地方。

@FrameworkEndpoint
public class TokenEndpoint extends AbstractEndpoint {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<OAuth2Exception> handleException(Exception e) throws Exception {
        logger.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage());
        return getExceptionTranslator().translate(e);
    }

以下是AbtractEndpoint的片段

public class AbstractEndpoint implements InitializingBean {

   protected final Log logger = LogFactory.getLog(getClass());

   private WebResponseExceptionTranslator providerExceptionHandler = new DefaultWebResponseExceptionTranslator();

   public void setProviderExceptionHandler(WebResponseExceptionTranslator providerExceptionHandler) {
       this.providerExceptionHandler = providerExceptionHandler;
   }

所以我的问题是。如何通过spring-security.xml调用setProviderExceptionHandler传递我的自定义类?

1 个答案:

答案 0 :(得分:7)

为了自定义spring-oauth的异常处理程序,您必须定义WebResponseExceptionTranslator的实例:

@Bean
public WebResponseExceptionTranslator webResponseExceptionTranslator() {
     return new DefaultWebResponseExceptionTranslator() {

         @Override
         public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
             ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);
             OAuth2Exception body = responseEntity.getBody();
             HttpHeaders headers = new HttpHeaders();
             headers.setAll(responseEntity.getHeaders().toSingleValueMap());
             // do something with header or response
             return new ResponseEntity<>(body, headers, responseEntity.getStatusCode());
         }
     };
 }

并将其传递给configurer的exceptionTranslator属性。我使用基于注释的配置,所以看起来像这样:

@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfiguration extends AuthorizationServerConfigurerAdapter {
    // some config

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .pathMapping("/oauth/authorize", "/authorize")
                .pathMapping("/oauth/error", "/error")
                .exceptionTranslator(webResponseExceptionTranslator())
        ;
    }
}

只需使用基于xml的配置检查<oauth:authorization-server />可用的属性。