Skip to main content

Setup a backend application

Prerequisites

Create a developer account in the Developer Console

Connect a backend through Developer Console's Applications page.

Project initialization

In this example, we are going to use Node.js to setup a simple example that implements the authentication flow, obtains the access token and creates a new scenario by using the Envizage API.

Fisrt things first, we should install Node.js on our system. Learn more about the ways you can install Node.js here.

Once we have installed Node.js, let's start building the example. In this example we are going to use Axios as HTTP Client and DotEnv package to load the environment variables from a .env file into the process.env object. Install Axios using the command:

npm install axios

or with Yarn:

yarn add axios

and DotEnv by running the following command on your terminal:

npm install dotenv

or with Yarn:

yarn add dotenv

Following the prerequisites and having connected a backend application, you should already obtained the values for client id and client secret. Those values are mandatory for the authentication flow implementation.

Create a .env file and add these values there. You can also add other global variables in this file, such as realm id, user's username and password or API's and authentication provider's URLs.

  REALM_ID="<realm_id>"
CLIENT_SECRET="<client_secret>"
CLIENT_ID="<client_id>"
USERNAME="<username>"
PASSWORD="<user_password>"
PROVIDER_URL="https://id.alpha.envizage.me"
API_URL="https://api.alpha.envizage.me"

Create authentication and services modules

Next, create a file named auth.js and another one named services.js. Auth.js file includes and exports the methods related to authentication, while the services.js module includes and exports the methods that are responsible for the communication with Envizage API.

require('dotenv').config();
const axios = require('axios');
const qs = require('qs');

const realmId = process.env.REALM_ID;
const url = process.env.PROVIDER_URL;

const getToken =(clientSecret, clientId)=>{
return axios({
method: 'post',
url: `${url}/realms/${realmId}/protocol/openid-connect/token`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
data: qs.stringify({
'grant_type': 'client_credentials',
'client_secret': clientSecret,
'client_id': clientId
})
})
};

const createUser = (username, password, token) => {
return axios({
method: 'post',
maxBodyLength: Infinity,
url: `${url}/admin/realms/${realmId}/users`,
headers: {
'Authorization': `Bearer ${token}`
},
data: {
"username": username,
"email": "",
"firstName": "",
"lastName": "",
"enabled": true,
"emailVerified": true,
"credentials": [
{
"type": "password",
"value": password
}
]
}
})
}

const getAccessToken = (clientSecret, clientId, username, password) => {
return axios({
method:'post',
maxBodyLength: Infinity,
url: `${url}/realms/${realmId}/protocol/openid-connect/token`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
},
data: {
'username': username,
'password': password,
'client_secret': clientSecret,
'client_id': clientId,
'grant_type': 'password'
}
})
}

module.exports = {
getToken,
createUser,
getAccessToken
}

Create new user

In order to obtain an access token and use the Envizage API, user's username and password are mandatory. In case you don't have any user registered, you can create a new user from Developer Console's Users page or programmaticaly by using getToken and createUser methods from auth.js like the example below:

require('dotenv').config();
const { getToken, createUser } = require('./auth');

const clientSecret = process.env.CLIENT_SECRET;
const clientId = process.env.CLIENT_ID;

async function createNewUser() {
try {
const getTokenResponse = await getToken(clientSecret, clientId);
const token = getTokenResponse?.data?.access_token;
createUser('username', 'password', token)
} catch (error) {
console.log(error)
}
}

createNewUser();

Execute the script by running the following command on your terminal:

node user.js

Get access token and use Envizage API

Create a file named app.js. You can use getAccessToken() method from auth.js to get the access token. Afterwards you can use this token to utilize the Envizage API. In the example below we have created a function named useEnvizageApi(). Inside this function, we first get the access token and then use createScenario() method from services.js file to create a new scenario.

require('dotenv').config();
const { getAccessToken } = require('./auth');
const { createScenario } = require('./services');

const clientSecret = process.env.CLIENT_SECRET;
const clientId = process.env.CLIENT_ID;
const username = process.env.USERNAME;
const password = process.env.PASSWORD;

async function useEnvizageApi() {
try {
const getTokenResponse = await getAccessToken(clientSecret, clientId, username, password);
const accessToken = getTokenResponse?.data?.access_token;
const createScenarioResponse = await createScenario(accessToken, {name: 'Me Today'});
} catch (error) {
console.log(error)
}
}

useEnvizageApi();

Execute the script by running the following command on your terminal:

node app.js