Skip to content

Instantly share code, notes, and snippets.

@niklas1375
Created June 22, 2021 07:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niklas1375/1ade5ccd099361060fb07b3d8844989c to your computer and use it in GitHub Desktop.
Save niklas1375/1ade5ccd099361060fb07b3d8844989c to your computer and use it in GitHub Desktop.
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