Edge デバイスセキュリティ要求の例
以下の例は、セキュリティ要求を Edge デバイスに追加して、ThingWorx Platform に送信する方法を示しています。
この例では、以下のことが行われます。
セキュリティ要求が送信されるターゲット ThingWorx Platform を定義します。
セキュリティ要求とターゲットプラットフォームの両方を設定して、Edge デバイスの API クライアントを定義します。
いくつかの無効な要求のセットと、1 つの有効なセキュリティ要求のセットを示して、セキュリティ要求がどのように処理されるか説明します。
import com.thingworx.communications.client.APIClient;
import com.thingworx.communications.client.ClientConfigurator;
import com.thingworx.communications.common.SecurityClaims;

public class TestCustomAuth {

private static final String THINGWORX_URI = "wss://${some.thingworx.
platform}:${thingworxPort}/Thingworx/WS";

public static void main(String[] args) throws Exception {
//create and configure a simple APIClient. This code requires the
//client SDK to function
ClientConfigurator clientConfiguration = new ClientConfigurator();
SecurityClaims claims = new SecurityClaims();
clientConfiguration.setSecurityClaims(claims);
clientConfiguration.setUri(THINGWORX_URI);
APIClient client = new APIClient(clientConfiguration);

//add claims that are not correct to the claims. This will result in
//a connection failure because the special key "secretTokenKey" was
//not supplied in the claims - even though the value supplied is the
//one we expect to work
claims.addClaim("thisIsNotTheCorrectSecretKey", "MySecretKey");
claims.addClaim("whoTheySaidTheyWere", "Administrator");
tryToConnect(client);

//now use the correct secret key token, but supply an invalid value
//and expect the client to still not connect
claims.addClaim("secretTokenKey", "correct key name - wrong value");
claims.addClaim("whoTheySaidTheyWere", "Administrator");
tryToConnect(client);

//supply the correct secret key, and the correct token, but a user
//that does not exist in the thingworx platform
claims.addClaim("secretTokenKey", "MySecretKey");
claims.addClaim("whoTheySaidTheyWere", "AdministratorDoesNotExist");
tryToConnect(client);

//supply the correct secret key, and the correct token, AND a user
//that exists. This time we expect to be connected using our custom
//edge authenticator
claims.addClaim("secretTokenKey", "MySecretKey");
claims.addClaim("whoTheySaidTheyWere", "Administrator");
tryToConnect(client);
}

private static void tryToConnect(APIClient client) throws Exception {
long waitUntil = System.currentTimeMillis() + 5000; //the time 5
//seconds in the future

//this method will simply try to connect over and over again
//if needed
while(!client.isConnected() && System.currentTimeMillis() <=
waitUntil) {
client.connect(); //try to connect and then sleep a bit waiting
// for it to succeed
Thread.sleep(100);
}

outputIfConnected(client);
}

private static void outputIfConnected(APIClient client) {
if(client.isConnected()) {
System.err.println("Congratulations! You ARE connected and you
used your custom edge authenticator");
} else {
System.err.println("NOT CONNECTED");
}
}
}