Spring Traverson and OAuth2RestTemplate

346 views Asked by At

I have an OAuth2RestTemplate to handle the communication with a REST-API and just tried to use this in combination with a Traverson, like so:

@Bean
public Traverson traverson( final OAuth2RestTemplate restTemplate ) {
   try {
      final Traverson traverson = new Traverson( new URI( this.baseUrl ), MediaType.APPLICATION_JSON );
      traverson.setRestOperations( restTemplate );
      return traverson;
   }
   catch ( final URISyntaxException e ) {
      throw new BeanCreationException( e );
   }
}

When trying to use the traverson now, the template handles the OAuth2 dance pretty well, fetching a token and all - yet the header Authorization: Bearer ... unfortunately won't be sent by the traverson.

So when I call an endpoint now, e.g. traverson.follow( "xyz" )... the result is only the login form of the REST API provider :-(

My question: Am I missing something or is my "OAuth2RestTemplate with Traverson" approach simply not supported or the traverson meant to be used in such a manner?

Any help appreciated! Currently I would say it simply isn't possible, yet most of the time in this "Spring world" there are ways to get it done - perhaps one of you knows how!

1

There are 1 answers

1
xvronny On

I think you need to set HAL message converters predefined in Traverson.

restTemplate.setMessageConverters(Traverson.getDefaultMessageConverters(mediaTypes));

In my case I've used an extension of Traverson to use the OAuth2 RestTemplate successfully.

public class ExtendedTraverson extends Traverson {

  public ExtendedTraverson(URI baseUri, RestTemplate restTemplate, List<MediaType> mediaTypes) {
    super(baseUri, mediaTypes);
    restTemplate.setMessageConverters(getDefaultMessageConverters(mediaTypes));
    setRestOperations(restTemplate);
  }

}