Edge 裝置安全性宣告範例
以下範例說明了如何將安全性宣告新增至 Edge 裝置並提交至 ThingWorx Platform。
此範例會執行下列操作:
定義要向其傳送安全性宣告的目標 ThingWorx Platform。
定義用於 Edge 裝置的 API 用戶端,會同時設定安全性宣告和目標平台。
經由提供數組無效的宣告和一組有效的安全性宣告,來藉此說明安全性宣告的處理方式。
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");
}
}
}