This article explains how to integrate the Cloud OAuth API into your web application.
To integrate your application, use the authorization URL (https://nxvms.com/authorize) along with the token requests described below. The authorization URL sends users to the Cloud login page, ensuring your application never sees their password.
Define variables
Define the following global variables to use throughout your code:
let tokens, access_token, refresh_token;
const url = new URL(window.location.href);
const cloudHost = 'https://nxvms.com';Build the OAuth URL
Create an OAuth authorization URL using your unique client ID and redirect URL:
client_id: A unique identifier registered with Nx Cloud (such as your app name).redirect_url: The URL where Nx Cloud sends the user after authentication—typically your application's current page URL.
const buildOauthUrl = () => {
const redirectUrl = new URL(`${cloudHost}/authorize`);
redirectUrl.searchParams.set('redirect_url', window.location.href);
redirectUrl.searchParams.set('client_id', '{something unique to your app}');
return redirectUrl.toString();
};Redirect the user
Redirect the browser to the authorization URL:
const redirectOauthLogin = (cloudAuthUrl) => {
window.location.href = cloudAuthUrl;
};Extract the authorization code
After the user logs in, Nx Cloud redirects the browser back to your redirect_url with an authorization code in the query parameters. Extract this code to generate access tokens:
const url = new URL(window.location.href);
const code = url.searchParams.get('code');Clean the URL (Optional)
Remove the code parameter from the URL bar after extracting it:
const cleanupCode = () => {
url.searchParams.delete('code');
window.history.pushState({}, undefined, url.toString());
};Exchange the authorization code for tokens
Send a POST request to Nx Cloud containing the authorization code to receive your initial access and refresh tokens:
const postWrapper = (url, data) => {
const options = {
headers: { 'Content-Type': 'application/json' },
method: "POST",
body: JSON.stringify(data)
};
return fetch(url, options).then(r => r.json());
};
const getTokensWithCode = (code) => {
const data = {
code,
grant_type: 'authorization_code',
response_type: 'token'
};
return postWrapper(`${cloudHost}/cdb/oauth2/token`, data);
};
tokens = await getTokensWithCode(code);
access_token = tokens.access_token;
refresh_token = tokens.refresh_token;Get a list of sites
Make a GET request using the access_token to fetch a list of available sites:
const getWrapper = (url, params) => {
const requestUrl = new URL(url);
requestUrl.search = new URLSearchParams(params).toString();
const options = {
method: "GET",
headers: {},
};
if (access_token) {
options.headers['Authorization'] = `Bearer ${access_token}`
}
return fetch(requestUrl.toString(), options).then(r => r.json());
};
const systems = await getWrapper(`${cloudHost}/cdb/systems`);Get a Site-scoped token
The primary access_token lists available sites, but it cannot make direct API calls to a specific site. Exchange your refresh_token for a token scoped to a specific site's cloudSystemId:
const getTokenForSystem = (systemId) => {
const data = {
refresh_token,
grant_type: "refresh_token",
response_type: "token",
scope: `cloudSystemId=${systemId}`
};
return postWrapper(`${cloudHost}/cdb/oauth2/token`, data).then((data) => data.access_token);
};Call a site using the Nx Cloud Relay
Each site is accessible at https://<site id>.relay.vmsproxy.com.
Because this host responds with an HTTP 307 redirect to a regional server, browsers automatically drop the Authorization header during the redirect. To work around this issue:
Send an unauthenticated request to resolve the redirect address.
Send your authenticated request directly to the final server URL.
NOTE: This workaround is only required for client-side JavaScript. Back-end servers, CLI tools, and curl -L automatically preserve the Authorization header across HTTP 307 redirects. |
const resolveRelayRedirect = async (url) => {
const probeResponse = await fetch(url.toString());
return probeResponse.url;
};
const systemGetWrapper = async (systemToken, url, params) => {
const requestUrl = new URL(url);
requestUrl.search = new URLSearchParams(params).toString();
const finalUrl = await resolveRelayRedirect(requestUrl);
const options = {
method: "GET",
headers: {},
};
if (systemToken) {
options.headers['Authorization'] = `Bearer ${systemToken}`
}
return fetch(finalUrl, options).then(r => r.json());
};
const cloudRelay = `https://${siteId}.relay.vmsproxy.com`;
const servers = await systemGetWrapper(systemAccessToken, `${cloudRelay}/rest/v4/servers`);
const cameras = await systemGetWrapper(systemAccessToken, `${cloudRelay}/rest/v4/devices`);Complete sample
To see the complete code example, visit the Nx Open GitHub repository (API Sample/web).
Comments
0 comments
Article is closed for comments.