title: Consuming REST API secured with Keycloak as Broker for OAUTH2-Provider
body: <p>I have to consume REST API of an app secured with Keycloak, which serves as Broker to OAUTH2-Provider. </p>
  
  <p>For this aim I use OAuth2RestTemplate and ResourceOwnerPasswordDetails.
  I can obtain an access token from third-part provider without any problem, but how have I use it further, it is the question. Using it in a Header as Bearer doesn't help. </p>
  
  <p>Any suggestions?</p>
  
  <p>OAuthConfig.java</p>
  
  <pre><code>@Bean
  public ResourceOwnerPasswordResourceDetails resource(){
  ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
  resource.setClientAuthenticationScheme(AuthenticationScheme.form);
  resource.setAccessTokenUri(env.getProperty("access.token.uri"));
  resource.setClientId(env.getProperty("access.client.id"));
  resource.setGrantType("password");
  resource.setClientSecret(env.getProperty("access.client.secret"));
  resource.setUsername(env.getProperty("access.client.username"));
  resource.setPassword(env.getProperty("access.client.password"));
  resource.setScope(Arrays.asList(env.getProperty("access.client.scope")));
  return resource;
  }
  </code></pre>
  
  <p>Service to obtain an Access Token</p>
  
  <pre><code>@Autowired
  private OAuthConfig authConfig;
  
  @Override
  public OAuth2AccessToken getAccessToken(){
  ResourceOwnerPasswordAccessTokenProvider provider = new ResourceOwnerPasswordAccessTokenProvider();
  OAuth2AccessToken accessToken = provider.obtainAccessToken(authConfig.resource(), new DefaultAccessTokenRequest());
  return accessToken;
  }
  </code></pre>
  
  <p>OAuth2RestTemplate</p>
  
  <pre><code>@Autowired private ProdAuthService authService;
  
  OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(authConfig.resource(), new DefaultOAuth2ClientContext(authService.getAccessToken())); 
  restTemplate.setRequestFactory(requestFactory);
  restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
  restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
  HttpHeaders header = new HttpHeaders();
  header.setContentType(MediaType.APPLICATION_JSON);
  header.set("Authorization", "Bearer " + authService.getAccessToken());
  HttpEntity&lt;String&gt; request = new HttpEntity&lt;String&gt;(header);
  ResponseEntity &lt;ProcessInstanceLogWrapper&gt; response = restTemplate.exchange(uri, HttpMethod.GET, request, new ParameterizedTypeReference&lt;ProcessInstanceLogWrapper&gt;(){});
  ProcessInstanceLogWrapper json = response.getBody();
  </code></pre>
  
  <p>An error I get</p>
  
  <pre><code>Caused by: org.springframework.security.oauth2.client.http.AccessTokenRequiredException: OAuth2 access denied.
  </code></pre>
  
  <p>In Keycloak we use also Authorizaion URL, but it seems not possible to use it with ResourceOwnerPasswordResourceDetails. It could also according to my opinion be the case, it doesn't work. </p>