Two authentication paradigms are available, OAuth2 (Client Credentials) and API keys. The OAuth method allows the greatest flexibility and security in allowing end-client applications to make API calls directly to the platform.
Three access paradigms are supported, with the first option being the preferred authentication flow:
auth_token using its Client Credentials.The following sequence diagram illustrates the recommended approach (option 1):
This API uses OAuth 2 authentication flows with the client_credentials grant_type for accessing all operations.
See the Authentication section for more detailed process information.
clientCredentials /auth/tokenobserver - Grants read-only observer access (currently not available)
user - Grants user-level access (currently not available)
admin - Grants admin-level access
You need to find the Event Hub/API hosting IP address before starting the coding steps. There are two ways to do so:
QuantumRTLS-[SERIALNUMBER] and the password is SpatialIntelligence. The hosting IP address by default is 10.42.0.1 To establish a connection to the SignalR Event Hub endpoint, it is first required to obtain an EndpointID by using the Connection Management API operation. After the new Event Hub connection request has been created, we are ready to connect to the Event Hub. Follow these steps to create a project that can connect to the Event Hub:
.razor file under "Pages" folder and name it "ConnectionTest.razor" 127.0.0.1 . Replace {YOUR USERNAME}} and {YOUR PASSWORD} with your own credential info.@using System.Text;
@using Microsoft.AspNetCore.SignalR.Client;
@using Newtonsoft.Json;
@page "/connectionTest"
<PageTitle>Connection Test</PageTitle>
<h1>Connection Test</h1>
@foreach (var item in m_receivedData)
{
<p>@item</p>
}
@code {
List<string> m_receivedData = new List<string>();
//Declaring some C# classes to store the results
private class AuthResponseData
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string scope { get; set; }
public AuthResponseUserData User { get; set; }
}
private class AuthResponseUserData
{
public string auth_id { get; set; }
public string AccessLevel { get; set; }
}
private class ApiKeyData
{
public string ApiKey { get; set; }
}
private class ConnectionData
{
public string EndpointURI { get; set; }
public string EndpointID { get; set; }
public HubInfo HubInfo { get; set; }
}
private class HubInfo
{
public string HubName { get; set; }
public string HubTypeID { get; set; }
public string HubInstanceID { get; set; }
}
protected override async Task OnInitializedAsync()
{
await StartConnectionAsync();
}
public async Task StartConnectionAsync()
{
var httpClient = new HttpClient();
var authDataJson = "{\"grant_type\":\"client_credentials\",\"auth_id\":\"{YOUR USERNAME}\",\"auth_secret\":\"{YOUR PASSWORD}\"}";
// Request OAuth token
var oauthTokenResponse = await httpClient.PostAsync("http://{API Host Here}:5000/v3/auth/token", new StringContent(authDataJson, Encoding.UTF8, "application/json"));
var oauthTokenJson = await oauthTokenResponse.Content.ReadAsStringAsync();
var oauthToken = JsonConvert.DeserializeObject<AuthResponseData>(oauthTokenJson);
// Register API Key
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {oauthToken.access_token}");
var apiKeyResponse = await httpClient.PostAsync("http://{API Host Here}:5000/v3/auth/registerApiKey", new StringContent(string.Empty));
var apiKeyJson = await apiKeyResponse.Content.ReadAsStringAsync();
var apiKey = JsonConvert.DeserializeObject<ApiKeyData>(apiKeyJson);
httpClient.DefaultRequestHeaders.Remove("Authorization");
//Default filter to only receive position events
var filterJson = "{\"Filters\":[{\"FilterTemplate\":\"position_events\"}]}";
//Request connection info
httpClient.DefaultRequestHeaders.Add("X-API-KEY", apiKey.ApiKey);
var connectionInfoResponse = await httpClient.PostAsync("http://{API Host Here}:5000/v3/events/connections", new StringContent(filterJson, Encoding.UTF8, "application/json"));
var connectionInfoJson = await connectionInfoResponse.Content.ReadAsStringAsync();
var connectionInfo = JsonConvert.DeserializeObject<ConnectionData>(connectionInfoJson);
//Build connection and handling of events
var eventHubConnection = new HubConnectionBuilder().WithUrl("http://{API Host Here}:33001/hubs/eventHub", //EndpointURI obtained from last step
(opts) =>
{
opts.AccessTokenProvider = () => Task.FromResult(connectionInfo.EndpointID); //EndpointID obtained from last step
}).Build();
var eventHubMessageSubscription = eventHubConnection.On<string>("Event", async (message) =>
{
//Handle the event here
m_receivedData.Add(message);
await InvokeAsync(StateHasChanged);
});
//Start the connection
await eventHubConnection.StartAsync();
}
}
Shared/NavMenu.razor file, insert the following code:<div class="nav-item px-3">
<NavLink class="nav-link" href="connectionTest">
<span class="oi oi-list-rich" aria-hidden="true"></span> Connection Test
</NavLink>
</div>
https to httpTo establish a connection to the SignalR Event Hub Endpoint, it is first required to obtain an EndpointID by using the Connection Management API operation. After the new Event Hub connection request has been created, we're ready to connect to the Event Hub. Follow these steps to create a project that can connect to the Event Hub:
.html file containing the following code: 127.0.0.1 . Replace {YOUR USERNAME}} and {YOUR PASSWORD} with your own credential info.<script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.js"></script>
<body>
<div id="container">
</div>
</body>
<script>
const eventHubUrl = "http://{API Host Here}:33001/hubs/eventHub"; // url of event hub signalR
const apiUrl = "http://{API Host Here}:5000/v3/"; // url of the EventHub API
$(document).ready(async function () {
var endpointID = await getEndpointID();
const connection = new signalR.HubConnectionBuilder()
.withUrl(eventHubUrl,
{
accessTokenFactory: () => {
return endpointID;
}
})
.configureLogging(signalR.LogLevel.Information)
.build();
connection.on("Event", data => {
// TODO: do something with data
var node = document.getElementById("container");
var newNode = document.createElement("p");
newNode.appendChild(document.createTextNode(data));
node.appendChild(newNode);
});
connection.onclose(async () => {
//TODO: do something for close event
});
await connection.start();
});
async function getEndpointID() {
var accessToken;
var endpointID;
try {
// Get the Bearer Token
await fetch(
apiUrl + "auth/token",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
grant_type: "client_credentials",
auth_id: "{YOUR USERNAME}",
auth_secret: "{YOUR PASSWORD}"
})
})
.then(response => response.json())
.then(result => {
accessToken = result["access_token"];
})
.catch(error => {
});
// Initiate connection details
await fetch(
apiUrl + "events/connections",
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${accessToken}`
},
body: JSON.stringify({
"Mode": "read",
"Filters": [{ "FilterTemplate": "position_events" }]
})
})
.then(response => response.json())
.then(result => {
endpointID = result["EndpointID"];
})
.catch(error => {
});
} catch (e) {
console.log(e);
}
return endpointID;
}
</script>
To establish a connection to the SignalR Event Hub endpoint, it is first required to obtain an EndpointID by using the Connection Management API operation. After the new Event Hub connection request has been created, we're ready to connect to the Event Hub. Follow these steps to create a project that can connect to the Event Hub:
pip in your terminal:pip install signalrcore==0.9.5
.py file containing the following code:import requests
import json
from signalrcore.hub_connection_builder import HubConnectionBuilder
eventHubUrl = "http://{API Host Here}:33001/hubs/eventHub" # Url of event hub signalR
apiUrl = "http://{API Host Here}:5000/v3/" # Url of the EventHub API
def main():
hub_connection = HubConnectionBuilder()\
.with_url(eventHubUrl,
options={
"access_token_factory": authenticateConnection
})\
.build()
hub_connection.on_open(lambda: print(
"connection opened and handshake received ready to send messages"))
hub_connection.on_close(lambda: print("connection closed"))
hub_connection.on("Event", print)
hub_connection.start()
def authenticateConnection():
# Get Bearer token
headers = {
"Content-Type": "application/json"
}
body = json.dumps({
"grant_type": "client_credentials",
"auth_id": "{YOUR USERNAME}",
"auth_secret": "{YOUR PASSWORD}"
})
authTokenResponse = requests.post(
apiUrl + "auth/token", headers=headers, data=body)
authToken = authTokenResponse.json()["access_token"]
# Initiate connection details to obtain EndpointID
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + authToken
}
body = json.dumps({
"QualityOfService": {
"MaxUpdateRate": 20,
"MaxThroughput": 10240,
"AutotuneConnectionParameters": False
},
"Mode": "read",
"Filters": [{"FilterTemplate": "position_events"}]
})
endpointIDResponse = requests.post(
apiUrl + "events/connections", headers=headers, data=body)
endpointID = endpointIDResponse.json()["EndpointID"]
return endpointID
if __name__ == "__main__":
main()
127.0.0.1 . Replace {YOUR USERNAME}} and {YOUR PASSWORD} with your own credential info..py file created by the terminal command:python -i ./FILE_NAME_CREATED.py
To establish a connection to the SignalR Event Hub endpoint, it is first required to obtain an EndpointID by using the Connection Management API operation. After the new Event Hub connection request has been created, we're ready to connect to the Event Hub. Follow these steps to create a project that can connect to the Event Hub:
build.gradle file, insert the following dependency under the dependencies section:implementation 'org.slf4j:slf4j-jdk14:1.7.25'
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
implementation 'org.apache.commons:commons-text:1.6'
implementation 'org.json:json:20231013'
SampleClass.java in the same directory of the App.java. And copy paste the code below:package javadoc;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Single;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class SampleClass {
private String eventHubUrl = "http://{API Host Here}/hubs/eventHub";
private String apiUrl = "http://{API Host Here}:5000/v3";
private String username = "{YOUR USERNAME}";
private String password = "{YOUR PASSWORD}";
public void init() throws Exception {
String token = getToken();
String eventHubApiKey = registerApikey(token);
HubConnection hubConnection = GetEventHubConnection(eventHubApiKey);
hubConnection.on("Event", (event) -> {
System.out.println(event);
}, String.class);
hubConnection.start();
}
public String getToken() throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("grant_type", "client_credentials");
jsonObject.put("auth_id", username);
jsonObject.put("auth_secret", password);
OkHttpClient client = new OkHttpClient.Builder().build();
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
Request request = new Request.Builder()
.url(apiUrl + "/auth/token")
.post(RequestBody.create(mediaType, jsonObject.toString()))
.build();
final String[] result = { null };
CountDownLatch latch = new CountDownLatch(1);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
latch.countDown();
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
JSONObject j_response;
String responseString = "";
try {
responseString = response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
if (!response.isSuccessful()) {
latch.countDown();
return;
} else {
try {
j_response = new JSONObject(responseString);
result[0] = j_response.getString("access_token");
} catch (Exception e) {
e.printStackTrace();
}
}
latch.countDown();
}
});
latch.await();
return result[0];
}
public String registerApikey(String apiToken) throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("grant_type", "client_credentials");
jsonObject.put("auth_id", username);
jsonObject.put("auth_secret", password);
OkHttpClient client = new OkHttpClient.Builder().build();
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
Request request = new Request.Builder()
.url(apiUrl + "/auth/registerApiKey")
.addHeader("Authorization", "Bearer " + apiToken)
.post(RequestBody.create(mediaType, jsonObject.toString()))
.build();
final String[] result = { null };
CountDownLatch latch = new CountDownLatch(1);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
latch.countDown();
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
JSONObject j_response;
String responseString = "";
try {
responseString = response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
if (!response.isSuccessful()) {
latch.countDown();
return;
} else {
try {
j_response = new JSONObject(responseString);
result[0] = j_response.getString("ApiKey");
} catch (Exception e) {
e.printStackTrace();
}
}
latch.countDown();
}
});
latch.await();
return result[0];
}
public HubConnection GetEventHubConnection(String eventHubApiKey) throws Exception {
String connectionId = GetConnectionID(eventHubApiKey);
HubConnection hubConnection = HubConnectionBuilder.create(eventHubUrl)
.withAccessTokenProvider(Single.defer(() -> {
return Single.just(connectionId);
})).build();
return hubConnection;
}
public String GetConnectionID(String eventHubApiKey) throws Exception {
JSONObject jsonObject = new JSONObject();
JSONArray filters = new JSONArray();
JSONObject filter = new JSONObject();
filter.put("FilterTemplate", "position_events");
filters.put(filter);
jsonObject.put("Filters", filters);
OkHttpClient client = new OkHttpClient.Builder().build();
MediaType mediaType = MediaType.parse("application/json;");
Request request = new Request.Builder()
.url(apiUrl + "/events/connections")
.post(RequestBody.create(mediaType, jsonObject.toString()))
.addHeader("X-API-KEY", eventHubApiKey)
.addHeader("Content-Type", "application/json")
.build();
final String[] result = { null };
CountDownLatch latch = new CountDownLatch(1);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
latch.countDown();
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
if (response.isSuccessful()) {
try {
JSONObject j_response = new JSONObject(response.body().string());
result[0] = j_response.getString("EndpointID");
} catch (JSONException e) {
e.printStackTrace();
}
}
latch.countDown();
}
});
latch.await();
return result[0];
}
}
App.java: SampleClass sample = new SampleClass();
String token = sample.getToken();
String eventHubApiKey = sample.registerApikey(token);
HubConnection hubConnection = sample.GetEventHubConnection(eventHubApiKey);
hubConnection.on("Event", (event) -> {
System.out.println(event);
}, String.class);
hubConnection.start();
127.0.0.1 . Replace {YOUR USERNAME}} and {YOUR PASSWORD} with your own credential info.