Consentric API

Using the Consentric API - NodeJS Step By Step Example​

Universal Consent & Preference Management... Made simple.

You may download a copy of the Source Code used in this guide here.

Prerequisites

When you signed up to Consentric you will have had an application created for you with some basic configuration and a client will have been configured for you to access the API. In order to work through this guide you will need the following details:

  • Your API client ID

  • Your API client secret

  • Your Consentric application ID

  • In ID of a privacy policy configured within your Consentric application

  • An ID of an Option configured within your Consentric application

  • An ID of a Permission Statement configured within your Consentric application

You will also need the following software installed

Obtaining Consentric Entity IDs

If you don’t know the prerequisite Consentric entity IDs, you can retrieve these from the Consentric admin UI.

When you log into the Consentric UI, assuming you have the correct privileges, in the top right there is a button that allows you to enter the admin UI:

Once logged into the admin UI you can obtain an ID for one of your configured options from within the ‘Configuration’ screen

Within the ‘Privacy Policies’ screen you can obtain the ID of the privacy policy you intend to use:

Within the ‘Permission Statements’ screen you can retrieve the ID of the permission statement you intend to use:

Building your NodeJS Client

First, create a new directory that you will store your code base in. In this example, we will call the directory ‘node-basic’.

$ mkdir node-basic
$ cd node-basic/ 

You will then need to initiate a new NodeJS project within this folder. This will track entrypoints, versioning and the packages we will need to install.

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (basic)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/alex/node-basic/package.json:

{
  "name": "basic",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes) yes
$ ls
package.json 

Now that you have a working project setup, you will want to create your source code file. Open up your favourite IDE and create a file called ‘index.js’. You should now have two files in your directory

$ ls
index.js     package.json 

The first thing we want to do in this project is to get a JWT (JSON Web Token) from Auth0 – this is the secure token that is going to allow the Node application to talk with the Consentric API. We can start by installing the Auth0 Node SDK – we will use the ‘npm command’ to do this.

$ npm install auth0
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN basic@1.0.0 No description
npm WARN basic@1.0.0 No repository field.

+ auth0@2.26.0
added 149 packages from 197 contributors and audited 149 packages in 5.471s

4 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

$ ls
index.js          node_modules      package-lock.json package.json 

Once this package is installed, we can begin writing code.

Open up index.js and insert the following code:

// Import required module
var AuthenticationClient = require('auth0').AuthenticationClient;

// Define Auth0 credentials here
var clientId = "<YOUR CLIENT ID>"
var clientSecret = "<YOUR CLIENT SECRET>"
var apiAudience = "https://api.consentric.io"

// Configure a new Auth0 Authentication Client
var auth0 = new AuthenticationClient({
  domain: 'consentric.eu.auth0.com',
  clientId: clientId,
  clientSecret: clientSecret,
}); 

In the code above we are importing the Auth0 Authentication Client, we are defining configuration values that will be used by the Authentication Client and finally we are initiating a new instance of an Authentication Client using the variables we have defined on lines 5 to 7.

Now we have an Authentication Client initiated, we can use this client to retrieve a token by calling the clientCredentialsGrant function:

// Request an Auth0 JWT
auth0.clientCredentialsGrant({
    audience: apiAudience
  },
  function(error, response) {
    if (error) throw new Error(error)

    console.log(response.access_token)
  }
) 

We can now run this code and see that it produces an Auth0 JWT for us and logs it to console.

> node index.js
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik5VUkRSVEZFUmtV........... 

We can now move onto making some requests to the Consentric API.

To make HTTP request to the Consentric API we will need to use a NodeJS package that will allow us to make outbound HTTP requests. In this case we are going to use a package called axios. You will need to use ‘npm’ to install this.

$ npm install axios
npm WARN basic@1.0.0 No description
npm WARN basic@1.0.0 No repository field.

+ axios@0.19.2
updated 1 package and audited 150 packages in 1.022s

4 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities 

Once the package is installed, we can import the package into our source code in the same manner we did with Auth0. Scroll back up to the top of your code base and add a new line after line 2.

 
// Import required modules
var AuthenticationClient = require('auth0').AuthenticationClient;
var axios = require('axios'); 

As we are now going to be communicating directly with the Consentric API, we need to define some new variables with the values you found earlier in this guide. These will be used later on.

// Define Consentric Options
var apiHost = "api.consentric.io"
var applicationId = "<YOUR APPLICATION ID>"
var externalRef = "<AN EXTERNAL REF FOR THE CITIZEN>"
var privacyPolicyId = "<YOUR PRIVACY POLICY ID>"
var permissionStatementId = "<YOUR PERMISSION STATEMENT ID>"
var optionId = "<YOUR OPTION ID>" 

Navigate in your code base to the line where you output the JWT using console.log and remove it. The function should then look like:

// Request an Auth0 JWT
auth0.clientCredentialsGrant({
    audience: apiAudience
  },
  function(error, response) {
    if (error) throw new Error(error)
    
    
  }
) 

We are going to start by creating a new Citizen in the Consentric Platform. This is done with a POST call to the /v1/citizens endpoint. In the request we will needs to specify the appropriate headers (including authentication) as well as the correct data to POST. Copy the following code:

// Create a Citizen
axios({
  method: 'POST',
  url: `https://${apiHost}/v1/citizens`,
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${response.access_token}`
  },
  data: {
    applicationId,
    externalRef,
    givenName: "Test",
    familyName: "Citizen",
    address: {
      streetAddress: "23 Acacia Avenue",
      addressLocality: "Trust Town",
      addressRegion: "Gloucestershire",
      addressCountry: "UK",
      postalCode: "TT1 1AS"
    }
  }
})
.then(data => {
  if (data.status != 200) throw new Error("Non-200 Response Code Detected")

  console.log("Citizen Created!")
  console.dir(data.data)
})
.catch(error => {
  console.log("Error creating Citizen")
  throw new Error(error)
}) 

If we now run the client, we should see the following:

$ node index.js
Citizen Created!
{
  citizenId: '<RANDOM UNIQUIE ID>',
  createdAt: '2020-06-25T10:20:42.966345Z',
  applicationDetails: [
    {
      name: 'Test Citizen',
      givenName: 'Test',
      familyName: 'Citizen',
      address: [Object],
      applicationId: '<YOUR APPLICATION ID>',
      externalRef: '<AN EXTERNAL REF FOR THE CITIZEN>'
    }
  ]
} 

Citizen contents and permissions are updated in Consentric by submitting transactions.

Each transaction can contain multiple changes to be applied and each change should specify the specific ‘Option’ to be changed and the new values to be applied.

A transaction should also state the IDs of the Privacy Policy and Permission Statement that that applied at the time the Citizen’s consents were obtained.

We want to ensure that we only try to create the transaction once the Citizen has already been created, so we will place the next block of code after console.dir(data.data) in the then block of the Citizen Create Axios statement.

// Create a Transaction
axios({
  method: 'POST',
  url: `https://${apiHost}/v1/permissions/transactions`,
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${response.access_token}`
  },
  data: {
    applicationId,
    externalRef,
    changes: {
      optionType: "option",
      optionId,
      justification: "consent",
      state: "GRANTED"
    },
    privacyPolicyId,
    permissionStatementId,
  }
})
.then(data => {
  if (data.status != 200) throw new Error("Non-200 Response Code Detected")

  console.log("Citizen Transaction Created!")
  console.dir(data.data)
})
.catch(error => {
  console.log("Error creating Transaction")
  throw new Error(error)
}) 

If we now run this, we should see the following:

$ node index.js
Citizen Created!
{
  citizenId: '<RANDOM UNIQUIE ID>',
  createdAt: '2020-06-25T10:38:15.473324Z',
  applicationDetails: [
    {
      name: 'Test Citizen',
      givenName: 'Test',
      familyName: 'Citizen',
      address: [Object],
      applicationId: '<YOUR APPLICATION ID>',
      externalRef: '<AN EXTERNAL REF FOR THE CITIZEN>'
    }
  ]
}
Citizen Transaction Created!
{
  transactions: [
    {
      id: 'F2xmNmH93LB_3hXjzjmwphf',
      applicationId: '<YOUR APPLICATION ID>',
      citizenId: '<RANDOM UNIQUE ID>',
      externalRef: '<YOUR EXTERNAL REF FOR THE CITIZEN>',
      changes: [Array],
      privacyPolicyId: '<YOUR PRIVACY POLICY ID>',
      privacyPolicyRef: 'policyRef-160',
      permissionStatementId: '<YOUR PERMISSION STATEMENT ID>',
      permissionStatementRef: 'ca041b40-482a-4630-9387-6fa8e38df634',
      recordedAt: '2020-06-25T10:38:15.854Z',
      recordedBySpecifiedByClient: false,
      recordedClient: 'AWW2hyrqOp3ctqy5wB6d9BuFFGh26Q63',
      revertable: true,
      obtainedAt: '2020-06-25T10:38:15.854Z'
    }
  ]
} 

The last step now is to pull all of this together and fetch the Citizens Permissions once the Transaction has been created. Copy the following code after console.dir(data.data) in the transaction create then block.

// Get Citizen Permissions
axios({
  method: 'GET',
  url: `https://${apiHost}/v1/permissions?applicationId=${applicationId}&externalRef=${externalRef}`,
  headers: {
    Authorization: `Bearer ${response.access_token}`
  }
})
.then(data => {
  if (data.status != 200) throw new Error("Status Code 200 was not found.")

  console.log("Citizen Permissions:")
  console.dir(data.data)
})
.catch(error => {
  console.log("Error getting permissions")
  throw new Error(error)
}) 

If we now run the code, we should see the following:

$ node index.js
Citizen Created!
{
  citizenId: '<RANDOM UNIQUIE ID>',
  createdAt: '2020-06-25T10:42:07.738503Z',
  applicationDetails: [
    {
      name: 'Test Citizen',
      givenName: 'Test',
      familyName: 'Citizen',
      address: [Object],
      applicationId: '<YOUR APPLICATION ID>',
      externalRef: '<AN EXTERNAL REF FOR THE CITIZEN>'
    }
  ]
}
Citizen Transaction Created!
{
  transactions: [
    {
      id: 'M9e68hCn2GT_n3NEz5VqSYL',
      applicationId: '<YOUR APPLICATION ID>',
      citizenId: '<RANDOM UNIQUE ID>',
      externalRef: '<YOUR EXTERNAL REF FOR THE CITIZEN>',
      changes: [Array],
      privacyPolicyId: '<YOUR PRIVACY POLICY ID>',
      privacyPolicyRef: 'policyRef-160',
      privacyPolicyId: '<YOUR PERMISSION STATEMENT ID>',
      permissionStatementRef: 'ca041b40-482a-4630-9387-6fa8e38df634',
      recordedAt: '2020-06-25T10:42:08.326Z',
      recordedBySpecifiedByClient: false,
      recordedClient: 'AWW2hyrqOp3ctqy5wB6d9BuFFGh26Q63',
      revertable: true,
      obtainedAt: '2020-06-25T10:42:08.326Z'
    }
  ]
}
Citizen Permissions:
{
  applicationId: '<YOUR APPLICATION ID>',
  citizenId: '<RANDOM UNIQUE ID>',
  externalRef: '<YOUR EXTERNAL REF FOR THE CITIZEN>',
  permissions: [
    {
      transactionId: 'M9e68hCn2GT_n3NEz5VqSYL',
      optionType: 'option',
      optionId: 'bPrQC',
      justification: 'consent',
      state: 'GRANTED',
      privacyPolicyId: '<YOUR PRIVACY POLICY ID>',
      privacyPolicyRef: 'policyRef-160',
      privacyPolicyId: '<YOUR PERMISSION STATEMENT ID>',
      permissionStatementRef: 'ca041b40-482a-4630-9387-6fa8e38df634',
      recordedClient: 'AWW2hyrqOp3ctqy5wB6d9BuFFGh26Q63',
      recordedAt: '2020-06-25T10:42:08.326Z',
      obtainedAt: '2020-06-25T10:42:08.326Z',
      validFrom: '2020-06-25T10:42:08.326Z',
      validUntil: '2022-06-25T10:42:08.326Z'
    }
  ]
} 

Well done – you are done! You have successfully created a Citizen in the Consentric Platform, recorded a consent transaction and retrieved their permissions!