Skip to content

Instantly share code, notes, and snippets.

@niklas1375
Created Jun 22, 2021
Embed
What would you like to do?
CF Service Facade with XsuaaTokenFlow
package my.util;
import java.net.URI;
import java.time.Instant;
import java.util.Map;
import com.sap.cloud.security.xsuaa.client.ClientCredentials;
import com.sap.cloud.security.xsuaa.client.DefaultOAuth2TokenService;
import com.sap.cloud.security.xsuaa.client.OAuth2TokenResponse;
import com.sap.cloud.security.xsuaa.client.XsuaaDefaultEndpoints;
import com.sap.cloud.security.xsuaa.tokenflows.XsuaaTokenFlows;
import lombok.Getter;
import io.pivotal.cfenv.core.CfCredentials;
import io.pivotal.cfenv.core.CfEnv;
public class CFServiceFacade {
private static CfEnv cfEnv = new CfEnv();
@Getter
private final Map<String, Object> serviceCredentials;
private OAuth2TokenResponse serviceTokenResponse;
public CFServiceFacade(String serviceInstanceName) {
CfCredentials cfCredentials = cfEnv.findCredentialsByName(serviceInstanceName);
serviceCredentials = cfCredentials.getMap();
}
public String getServiceJWT(String tokenServiceUrlProperty) {
if (serviceTokenResponse != null) {
if (Instant.now().compareTo(serviceTokenResponse.getExpiredAt()) > 0) {
// token is expired --> refresh
serviceTokenResponse = null;
return getServiceJWT(tokenServiceUrlProperty);
}
return serviceTokenResponse.getAccessToken();
}
try {
URI xsuaaUri = new URI((String) serviceCredentials.get(tokenServiceUrlProperty));
String clientid = (String) serviceCredentials.get("clientid");
String clientsecret = (String) serviceCredentials.get("clientsecret");
// use the XSUAA client library to ease the implementation of the user token
// exchange flow
XsuaaTokenFlows tokenFlows = new XsuaaTokenFlows(
new DefaultOAuth2TokenService(),
new XsuaaDefaultEndpoints(xsuaaUri.toString()),
new ClientCredentials(clientid, clientsecret));
serviceTokenResponse = tokenFlows.clientCredentialsTokenFlow().execute();
return serviceTokenResponse.getAccessToken();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public String getServiceProperty(String propertyName) {
return (String) serviceCredentials.get(propertyName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment