com.sap.cloud.security.xsuaa.client.XsuaaOAuth2TokenService Maven / Gradle / Ivy
/**
* SPDX-FileCopyrightText: 2018-2023 SAP SE or an SAP affiliate company and Cloud Security Client Java contributors
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.sap.cloud.security.xsuaa.client;
import com.sap.cloud.security.servlet.MDCHelper;
import com.sap.cloud.security.xsuaa.http.HttpHeaders;
import com.sap.cloud.security.xsuaa.tokenflows.TokenCacheConfiguration;
import com.sap.cloud.security.xsuaa.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestOperations;
import org.springframework.web.util.UriComponentsBuilder;
import javax.annotation.Nonnull;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static com.sap.cloud.security.xsuaa.Assertions.assertNotNull;
import static com.sap.cloud.security.xsuaa.client.OAuth2TokenServiceConstants.*;
/**
* Implementation for Spring applications, that uses {@link RestOperations}.
*/
public class XsuaaOAuth2TokenService extends AbstractOAuth2TokenService {
private static final Logger LOGGER = LoggerFactory.getLogger(XsuaaOAuth2TokenService.class);
private final RestOperations restOperations;
public XsuaaOAuth2TokenService(@Nonnull RestOperations restOperations) {
this(restOperations, TokenCacheConfiguration.defaultConfiguration());
}
public XsuaaOAuth2TokenService(@Nonnull RestOperations restOperations,
@Nonnull TokenCacheConfiguration tokenCacheConfiguration) {
super(tokenCacheConfiguration);
assertNotNull(restOperations, "restOperations is required");
this.restOperations = restOperations;
}
@Override
protected OAuth2TokenResponse requestAccessToken(URI tokenEndpointUri, HttpHeaders headers,
Map parameters) throws OAuth2ServiceException {
// Create URI
UriComponentsBuilder builder = UriComponentsBuilder.fromUri(tokenEndpointUri);
URI requestUri = builder.build().encode().toUri();
org.springframework.http.HttpHeaders springHeaders = new org.springframework.http.HttpHeaders();
headers.getHeaders().forEach(h -> springHeaders.add(h.getName(), h.getValue()));
springHeaders.add(MDCHelper.CORRELATION_HEADER, MDCHelper.getOrCreateCorrelationId());
springHeaders.add(org.springframework.http.HttpHeaders.USER_AGENT, HttpClientUtil.getUserAgent());
// Create entity
HttpEntity> requestEntity = new HttpEntity<>(copyIntoForm(parameters),
springHeaders);
@SuppressWarnings("rawtypes")
ResponseEntity