Cześć,
wiem że OAuth2RestTemplate jest już Deprecated i powinno się odejść od tego, ale wystąpił błąd podczas komunikacji z zewn. systemem, gdzie komunikujemy się właśnie za pomocą tego. Chcieliśmy uzyskać jakiś wgląd na to co się dzieje dokładniej i zalogować sobie dokładniej req/resp, co dokładnie tam ślemy, więc chcieliśmy dorzucić jakiś interceptor aby zobaczyć co dokładnie leci i co dokładnie otrzymujemy. Po token mieliśmy uderzać w formie: application/x-www-form-urlencoded
dając w headerze Authorization: Base64(clientId:clientSecret)
+ jako body username
, password
, grant_type
i scope
.
Tutaj bean dla RT:
@Configuration
public class SampleConfig {
@Bean
public OAuth2RestTemplate restTemplate () {
final ResourceOwnerPasswordResourceDetails details = new ResourceOwnerPasswordResourceDetails();
details.setPassword("password");
details.setUsername("username");
details.setClientId("clientId");
details.setClientSecret("clientSecret");
details.setAccessTokenUri("http://uri/v1/oauth/token");
details.setGrantType("password");
final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(details);
final List<ClientHttpRequestInterceptor> interceptors = oAuth2RestTemplate.getInterceptors();
interceptors.add(new LoggingInterceptor);
oAuth2RestTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(oAuth2RestTemplate.getRequestFactory()));
oAuth2RestTemplate.setInterceptors(interceptors);
return oAuth2RestTemplate;
}
}
Tu nasz przykładowy interceptor:
@Component
public class LoggingInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(
HttpRequest req, byte[] reqBody, ClientHttpRequestExecution ex) throws IOException {
LOGGER.debug("Request body: {}", new String(reqBody, StandardCharsets.UTF_8));
LOGGER.debug("Headers: {}", req.getHeaders().toSingleValueMap().entrySet()
.stream().map(it -> it.getKey() + " : " + it.getValue())
.collect(Collectors.joining(",", "{", "}")));
ClientHttpResponse response = ex.execute(req, reqBody);
InputStreamReader isr = new InputStreamReader(
response.getBody(), StandardCharsets.UTF_8);
String body = new BufferedReader(isr).lines()
.collect(Collectors.joining("\n"));
LOGGER.debug("Response body: {}", body);
return response;
}
}
Na koniec jakieś tam wywołanie tego:
@Component
public class SampleClient {
private final OAuth2RestTemplate auth2RestTemplate;
...
void sample() {
final ResponseEntity<String> response = auth2RestTemplate.getForEntity("http://uri/v1/data", String.class);
}
}
No i jak się okazuje to Interceptor jest wewnątrz tego RT, natomiast w ogóle nie wchodzi do metody intercept()
. Na debugu w ogóle się tam nie zatrzymuje, co może być tu powodem?
Z góry dzięki.