Skip to content
This repository has been archived by the owner on Jan 19, 2024. It is now read-only.

Commit

Permalink
Added OAuth2 support
Browse files Browse the repository at this point in the history
* Added OAuth2 support.
* Added context switching support for OAuth2
* Fixed bug caused by accessToken expiration.
  • Loading branch information
sfdrogojan authored May 15, 2019
1 parent e76eaa6 commit 3192d9d
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 21 deletions.
14 changes: 4 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,10 @@ Java platform. Among other things, the SDK:
For more information about the Java SDK and how to use it, please see
the Javadocs at http://salesforce-marketingcloud.github.io/FuelSDK-Java/.

New Features in Version 1.3.2
New Features in Version 1.4.0
------------
* Added support for your tenant’s endpoints - [More Details](https://developer.salesforce.com/docs/atlas.en-us.mc-apis.meta/mc-apis/your-subdomain-tenant-specific-endpoints.htm)
* REST, Auth endpoints are configurable. If not specified in the fuelsdk.properties file,
they are defaulted to "https://www.exacttargetapis.com" for REST and
"https://auth.exacttargetapis.com" for Auth.
* SOAP endpoint is also configurable. If not specified in the fuelsdk.properties file,
it is defaulted to "https://webservice.exacttarget.com/service.asmx"
* Removed the legacyToken query string parameter support.

* Added support for OAuth2 authentication - [More Details](https://developer.salesforce.com/docs/atlas.en-us.mc-app-development.meta/mc-app-development/integration-considerations.htm)
* To enable OAuth2 authentication, set `useOAuth2Authentication=true` in the fuelsdk.properties file.

Installation
------------
Expand All @@ -44,7 +38,7 @@ The easiest way to install the Java SDK is via Maven—simply add the follow
<dependency>
<groupId>com.github.salesforce-marketingcloud</groupId>
<artifactId>fuelsdk</artifactId>
<version>1.3.2</version>
<version>1.4.0</version>
</dependency>

Maven will automatically resolve, download, and install all dependencies for you.
Expand Down
5 changes: 5 additions & 0 deletions fuelsdk.properties.template
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
clientId=xxxxxxx
clientSecret=###########################
authEndpoint=https://auth.exacttargetapis.com
endpoint=https://########.rest.marketingcloudapis.com
soapEndpoint=https://########.soap.marketingcloudapis.com/service.asmx
useOAuth2Authentication=false
accountId=
scope=
dataExtensionFolderId=
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.github.salesforce-marketingcloud</groupId>
<artifactId>fuelsdk</artifactId>
<version>1.3.2</version>
<version>1.4.0</version>
<name>Salesforce Marketing Cloud Java SDK</name>
<description>Salesforce Marketing Cloud Java SDK</description>
<url>https://github.com/salesforce-marketingcloud/FuelSDK-Java</url>
Expand Down
93 changes: 86 additions & 7 deletions src/main/java/com/exacttarget/fuelsdk/ETClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ public class ETClient {
"https://auth.exacttargetapis.com";
private static final String PATH_REQUESTTOKEN =
"/v1/requestToken";
private static final String PATH_OAUTH2TOKEN =
"/v2/token";
private static final String PATH_ENDPOINTS_SOAP =
"/platform/v1/endpoints/soap";
private static final String DEFAULT_SOAP_ENDPOINT =
Expand Down Expand Up @@ -100,6 +102,9 @@ public class ETClient {
private static long soapEndpointExpiration = 0;
private static String fetchedSoapEndpoint = null;
private static final long cacheDurationInMillis = 1000 * 60 * 10; // 10 minutes
private boolean useOAuth2Authentication;
private String accountId;
private String scope;

/**
* Class constructor, Initializes a new instance of the class.
Expand Down Expand Up @@ -154,11 +159,15 @@ public ETClient(ETConfiguration configuration)
gson = gsonBuilder.create();
}

useOAuth2Authentication = configuration.isTrue("useOAuth2Authentication") ? true : false;
accountId = configuration.get("accountId");
scope = configuration.get("scope");

if (clientId != null && clientSecret != null) {
authConnection = new ETRestConnection(this, authEndpoint, true);
requestToken();
restConnection = new ETRestConnection(this, endpoint);
FetchSoapEndpoint();
fetchSoapEndpoint();
soapConnection = new ETSoapConnection(this, soapEndpoint, accessToken);
} else {
if (username == null || password == null) {
Expand Down Expand Up @@ -191,7 +200,11 @@ public ETClient(ETConfiguration configuration)
}
}

private void FetchSoapEndpoint() {
private void fetchSoapEndpoint() {
if(useOAuth2Authentication) {
return;
}

if (soapEndpoint == null || soapEndpoint.equals("")) {
//
// If a SOAP endpoint isn't specified automatically determine it:
Expand Down Expand Up @@ -313,6 +326,70 @@ public synchronized String requestToken()
return requestToken(null);
}

private synchronized String requestOAuth2Token()
throws ETSdkException
{
if (clientId == null || clientSecret == null) {
// no-op
return null;
}
//
// Construct the JSON payload.
//

JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("client_id", clientId);
jsonObject.addProperty("client_secret", clientSecret);
jsonObject.addProperty("grant_type", "client_credentials");
if(accountId != null && accountId.length() > 0)
{
jsonObject.addProperty("account_id", accountId);
}
if(scope != null && scope.length() > 0)
{
jsonObject.addProperty("scope", scope);
}

String requestPayload = gson.toJson(jsonObject);

ETRestConnection.Response response = null;

response = authConnection.post(PATH_OAUTH2TOKEN, requestPayload);

if (response.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new ETSdkException("error obtaining OAuth2 access token "
+ "("
+ response.getResponseCode()
+ " "
+ response.getResponseMessage()
+ ")");
}

//
// Parse the JSON response into the appropriate instance
// variables:
//

String responsePayload = response.getResponsePayload();

JsonParser jsonParser = new JsonParser();
jsonObject = jsonParser.parse(responsePayload).getAsJsonObject();
this.accessToken = jsonObject.get("access_token").getAsString();
this.expiresIn = jsonObject.get("expires_in").getAsInt();
this.endpoint = jsonObject.get("rest_instance_url").getAsString();
this.soapEndpoint = jsonObject.get("soap_instance_url").getAsString() + "service.asmx";

//
// Calculate the token expiration time. As before,
// System.currentTimeMills() is in milliseconds so
// we multiply expiresIn by 1000:
//

tokenExpirationTime = System.currentTimeMillis() + (expiresIn * 1000);

return accessToken;
}

/**
*
* @param refreshToken The refresh token
Expand All @@ -321,6 +398,10 @@ public synchronized String requestToken()
public synchronized String requestToken(String refreshToken)
throws ETSdkException
{
if(useOAuth2Authentication){
return requestOAuth2Token();
}

if (clientId == null || clientSecret == null) {
// no-op
return null;
Expand Down Expand Up @@ -418,15 +499,13 @@ public synchronized String refreshToken()
}

logger.debug("refreshing access token...");

if (refreshToken == null) {
throw new ETSdkException("refreshToken == null");
}
}

requestToken(refreshToken);

soapConnection.setAccessToken(accessToken);
if(soapConnection != null) {
soapConnection.setAccessToken(accessToken);
}

return accessToken;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ private HttpURLConnection sendRequest(URL url, Method method, String payload)
try {
connection = (HttpURLConnection) url.openConnection();

connection.setRequestProperty("User-Agent", "FuelSDK-Java-v1.3.2-REST-"+method+"-"+object);
connection.setRequestProperty("User-Agent", "FuelSDK-Java-v1.4.0-REST-"+method+"-"+object);
connection.setRequestMethod(method.toString());
} catch (ProtocolException ex) {
throw new ETSdkException("error setting request method: " + method.toString(), ex);
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/exacttarget/fuelsdk/ETSoapConnection.java
Original file line number Diff line number Diff line change
Expand Up @@ -234,12 +234,12 @@ public Soap getSoap() {
}

public Soap getSoap(String m) {
soapClient.getRequestContext().put("HTTP_HEADER_USER_AGENT", "FuelSDK-Java-v1.3.2-SOAP-"+m);
soapClient.getRequestContext().put("HTTP_HEADER_USER_AGENT", "FuelSDK-Java-v1.4.0-SOAP-"+m);
return soap;
}

public Soap getSoap(String m, String o) {
soapClient.getRequestContext().put("HTTP_HEADER_USER_AGENT", "FuelSDK-Java-v1.3.2-SOAP-"+m+"-"+o);
soapClient.getRequestContext().put("HTTP_HEADER_USER_AGENT", "FuelSDK-Java-v1.4.0-SOAP-"+m+"-"+o);
return soap;
}

Expand Down

0 comments on commit 3192d9d

Please sign in to comment.