How to change MediaType for MappingJacksonHttpMessageConverter in OAuth2RestTemplate

南笙酒味 提交于 2019-12-06 12:23:17

Fixed! The problem was that the OAuth2RestTemplate isn't used for token retrieval. So I had to customize the org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport and add the MappingJacksonHttpMessageConverter to the existing method like this:

  public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
    this.messageConverters = new ArrayList<HttpMessageConverter<?>>(messageConverters);
    this.messageConverters.add(new FormOAuth2AccessTokenMessageConverter());
    this.messageConverters.add(new FormOAuth2ExceptionHttpMessageConverter());

    MappingJacksonHttpMessageConverter jackson = new MappingJacksonHttpMessageConverter();
    List<MediaType> mediaTypes = new ArrayList<MediaType>();
    mediaTypes.add(new MediaType("application", "x-javascript"));
    jackson.setSupportedMediaTypes(mediaTypes);
    this.messageConverters.add(jackson);

    if(logger.isDebugEnabled())
    {
        logger.debug("*** Added custom media type 'application/x-javascript' to the Jackson converter");
    }
}

I came to this question by searching for "oauth RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type"

your answer was the hint I needed to solve the problem! I added the following Maven dependencies (which are optional in the oauth2 pom):

<!-- spring oauth2 json dependency: -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.3.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.3.2</version>
</dependency>

When creating the AuthorizationCodeAccessTokenProvider i added the jackson message converter:

protected AuthorizationCodeAccessTokenProvider getAccessTokenProvider() {
    final AuthorizationCodeAccessTokenProvider oAuthProvider = new AuthorizationCodeAccessTokenProvider();
    final List<HttpMessageConverter<?>> messageConv = new ArrayList<HttpMessageConverter<?>>();
    messageConv.add(new MappingJackson2HttpMessageConverter());
    oAuthProvider.setMessageConverters(messageConv);
    return oAuthProvider;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!