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");
}
}
}