OAuth2

A guide on how to implement an OAuth2 flow for authenticating our REST API.

Overview

This guide aims to provide the basic understanding and ability to authenticate a Service Account for REST API integrations. Core concepts about the OAuth2 authentication flow are briefly explained, and an example implementation is provided. The implementation is tested using the returned access token to send a request to the REST API to list all available projects.

Prerequisites

  • Service Account Credentials A Service Account must be created with a membership in the target project. Any role will suffice.

Example Code

The provided example code can be summarized by the following points.

  • A JSON Web Token (JWT) is constructed and signed with a secret.

  • The JWT is exchanged for an access token.

  • The Access token is used to authenticate the REST API.

The implemented OAuth2 authentication flow is based on the RFC7523 specification.

Environment Setup

If you wish to run the code locally, make sure you have a working runtime environment.

Python 3.9
Python API
Node.js 14
Go 1.16
Python 3.9

The following packages are required by the example code and must be installed.

pip install pyjwt==2.1.0
pip install requests==2.25.1
Python API

The Disruptive Technologies Python API can be installed through pip.

pip install --upgrade disruptive
Node.js 14

The following modules are required by the example code and must be installed.

npm install [email protected]
npm install [email protected]
Go 1.16

The following packages are required by the example code and must be installed.

go get github.com/dgrijalva/[email protected]

Add the following environment variables as they will be used in the authentication flow.

Bash
Bash
export DT_SERVICE_ACCOUNT_KEY_ID=<YOUR_SERVICE_ACCOUNT_KEY_ID>
export DT_SERVICE_ACCOUNT_SECRET=<YOUR_SERVICE_ACCOUNT_SECRET>
export DT_SERVICE_ACCOUNT_EMAIL=<YOUR_SERVICE_ACCOUNT_EMAIL>

Source

Python 3.9
Python API
Node.js 14
Go 1.16
Python 3.9
import os
import time
import jwt # pip install pyjwt==2.1.0
import requests # pip install requests==2.25.1
# Authentication details used in the OAuth2 flow.
SERVICE_ACCOUNT_KEY_ID = os.environ.get('DT_SERVICE_ACCOUNT_KEY_ID')
SERVICE_ACCOUNT_SECRET = os.environ.get('DT_SERVICE_ACCOUNT_SECRET')
SERVICE_ACCOUNT_EMAIL = os.environ.get('DT_SERVICE_ACCOUNT_EMAIL')
def get_access_token(key_id, email, secret):
# Construct the JWT header.
jwt_headers = {
'alg': 'HS256',
'kid': key_id,
}
# Construct the JWT payload.
jwt_payload = {
'iat': int(time.time()), # current unixtime
'exp': int(time.time()) + 3600, # expiration unixtime
'aud': 'https://identity.disruptive-technologies.com/oauth2/token',
'iss': email,
}
# Sign and encode JWT with the secret.
encoded_jwt = jwt.encode(
payload=jwt_payload,
key=secret,
algorithm='HS256',
headers=jwt_headers,
)
# Prepare HTTP POST request data.
# note: The requests package applies Form URL-Encoding by default.
request_data = {
'assertion': encoded_jwt,
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer'
}
# Exchange the JWT for an access token.
access_token_response = requests.post(
url='https://identity.disruptive-technologies.com/oauth2/token',
headers={'Content-Type': 'application/x-www-form-urlencoded'},
data=request_data,
)
# Halt if response contains an error.
if access_token_response.status_code != 200:
print('Status Code: {}'.format(access_token_response.status_code))
print(access_token_response.json())
return None
# Return the access token in the request.
return access_token_response.json()['access_token']
def main():
# Get an access token using an OAuth2 authentication flow.
access_token = get_access_token(
SERVICE_ACCOUNT_KEY_ID,
SERVICE_ACCOUNT_EMAIL,
SERVICE_ACCOUNT_SECRET,
)
# Verify that we got a valid token back.
if access_token is None:
return
# Test the token by sending a GET request for a list of projects.
print(requests.get(
url='https://api.disruptive-technologies.com/v2/projects',
headers={'Authorization': 'Bearer ' + access_token},
).json())
if __name__ == '__main__':
main()
Python API
import os
import disruptive as dt
# It is good practice to fetch credentials from an environment or file.
key_id = os.environ.get('DT_SERVICE_ACCOUNT_KEY_ID', '')
secret = os.environ.get('DT_SERVICE_ACCOUNT_SECRET', '')
email = os.environ.get('DT_SERVICE_ACCOUNT_EMAIL', '')
# Using the fetched credentials, authenticate the package.
dt.default_auth = dt.Auth.service_account(key_id, secret, email)
Node.js 14
const jwt = require('jsonwebtoken') // npm install [email protected]
const axios = require('axios').default // npm install [email protected]
// authentication details
const serviceAccountKeyID = process.env.DT_SERVICE_ACCOUNT_KEY_ID
const serviceAccountSecret = process.env.DT_SERVICE_ACCOUNT_SECRET
const serviceAccountEmail = process.env.DT_SERVICE_ACCOUNT_EMAIL
// Creates a JWT from the arguments, and exchanges it for an
// access token which is returned as a promise. If an error
// occurs at any point, an error is thrown and the returned
// promise is rejected.
async function getAccessToken(keyID, email, secret) {
// Construct the JWT header.
let jwtHeaders = {
'alg': 'HS256',
'kid': keyID,
}
// Construct the JWT payload.
let jwtPayload = {
'iat': Math.floor(Date.now() / 1000), // current unixtime
'exp': Math.floor(Date.now() / 1000) + 3600, // expiration unixtime
'aud': 'https://identity.disruptive-technologies.com/oauth2/token',
'iss': email,
}
// Sign and encode JWT with the secret.
const jwtEncoded = jwt.sign(
jwtPayload,
secret,
{
header: jwtHeaders,
algorithm: 'HS256',
},
)
// Prepare POST request data.
const requestObject = {
'assertion': jwtEncoded,
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
}
// Converts the requestObject to a Form URL-Encoded string.
const requestData = Object.keys(requestObject).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(requestObject[key])
}).join('&')
// Exchange JWT for access token.
const accessTokenResponse = await axios({
method: 'POST',
url: 'https://identity.disruptive-technologies.com/oauth2/token',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: requestData,
}).catch(function (error) {
// Prints the error response (if any), an re-throws the error.
if (error.response) {
console.log(error.response.data)
}
throw error
})
// Return the access token in the request.
return accessTokenResponse.data.access_token
}
async function main() {
// Get an access token using an OAuth2 authentication flow.
const accessToken = await getAccessToken(
serviceAccountKeyID,
serviceAccountEmail,
serviceAccountSecret,
)
// Test the token by sending a GET request for a list of projects.
const response = await axios({
method: 'GET',
url: 'https://api.disruptive-technologies.com/v2/projects',
headers: { 'Authorization': 'Bearer ' + accessToken },
})
// Print response data.
console.log(JSON.stringify(response.data, null, 2))
}
main()
Go 1.16
package main
import (
"encoding/json"
"fmt"
jwt "github.com/dgrijalva/jwt-go" // go get github.com/dgrijalva/[email protected]
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
)
const (
tokenEndpoint = "https://identity.disruptive-technologies.com/oauth2/token"
listDevicesEndpoint = "https://api.d21s.com/v2/projects"
)
func getAccessToken(keyID string, secret string, email string) (string, error) {
// Construct the JWT header.
jwtHeader := map[string]interface{}{
"alg": "HS256",
"kid": keyID,
}
// Construct the JWT payload. (Claims in golang)
jwtPayload := &jwt.StandardClaims{
IssuedAt: time.Now().Unix(), // current unixtime
ExpiresAt: time.Now().Add(1 * time.Hour).Unix(), // expiration unixtime
Audience: tokenEndpoint,
Issuer: email,
}
// Sign and encode JWT with the secret.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwtPayload)
token.Header = jwtHeader
encodedJwt, _ := token.SignedString([]byte(secret))
// Prepare HTTP POST request data.
// note: Form URL-Encode required and applied with .Encode()
reqData := url.Values{
"assertion": {encodedJwt},
"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"},
}.Encode()
// Create a new request object.
req, err := http.NewRequest(
"POST",
tokenEndpoint,
strings.NewReader(reqData),
)
if err != nil {
return "", err
}
// Set request headers.
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// Create a client and send the request.
client := &http.Client{Timeout: time.Second * 3}
res, err := client.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
type AuthResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
}
// Convert response body to AuthResponse.
var authResponse AuthResponse
if err := json.NewDecoder(res.Body).Decode(&authResponse); err != nil {
return "", err
}
// Return the access token string.
return authResponse.AccessToken, nil
}
func listProjects(accessToken string) error {
// Create the request object with method, URL, but no optional body.
req, err := http.NewRequest("GET", listDevicesEndpoint, nil)
if err != nil {
return err
}
// Set the authentication header with access token.
req.Header.Set("Authorization", "Bearer "+accessToken)
// Create a custom http Client with timeout.
client := &http.Client{Timeout: time.Second * 3}
// Send an HTTP request and return an HTTP response.
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
type ProjectsResponse struct {
Projects []struct {
Name string `json:"name"`
DisplayName string `json:"displayName"`
Inventory bool `json:"inventory"`
Organization string `json:"organization"`
OrganizationDisplayName string `json:"organizationDisplayName"`
SensorCount int `json:"sensorCount"`
CloudConnectorCount int `json:"cloudConnectorCount"`
}
NextPageToken string `json:"nextPageToken"`
}
var response ProjectsResponse
if err = json.NewDecoder(res.Body).Decode(&response); err != nil {
return err
}
// Print information about the projects.
for _, project := range response.Projects {
fmt.Println(project.DisplayName)
fmt.Printf("\t%d Sensors\n", project.SensorCount)
fmt.Printf("\t%d Cloud Connectors\n", project.CloudConnectorCount)
}
return nil
}
func main() {
// OAuth2 authentication flow
accessToken, err := getAccessToken(
os.Getenv("DT_SERVICE_ACCOUNT_KEY_ID"),
os.Getenv("DT_SERVICE_ACCOUNT_SECRET"),
os.Getenv("DT_SERVICE_ACCOUNT_EMAIL"),
)
if err != nil {
log.Fatal(err)
}
// Test the access token by listing all projects.
if err := listProjects(accessToken); err != nil {
log.Fatal(err)
}
}

Authentication Flow

Authenticating a client is a 3 step process, as illustrated below. Using both the figure and example code, the following sections will explain in more detail what each step entails.

Create the JWT
Exchange for Access Token
Access the REST API
Create the JWT
Exchange for Access Token
Access the REST API

Create the JWT

A JSON Web Token (JWT) contains three fields:

  1. Header: Token type and signature algorithm.

  2. Payload: Claims and additional data.

  3. Signature: A signature calculated of the entire JWT + a private secret.

Before being sent, these fields are each Base64Url encoded. They are combined in a compact dot format in the form Base64Url(header).Base64Url(payload).Base64Url(signature), which is what we will refer to as the encoded JWT.

This guide will not cover much more details of JWT. For a great introduction on JWT that provides an interactive editor and an exhaustive list of client libraries, please see jwt.io.

Using your Service Account credentials, construct the JWT headers and payload. Here, iat is the issuing time, and exp the expiration time of a maximum 1 hour after iat.

Python 3.9
Node.js 14
Go 1.16
Python 3.9
# Construct the JWT header.
jwt_headers = {
'alg': 'HS256',
'kid': key_id,
}
# Construct the JWT payload.
jwt_payload = {
'iat': int(time.time()), # current unixtime
'exp': int(time.time()) + 3600, # expiration unixtime
'aud': 'https://identity.disruptive-technologies.com/oauth2/token',
'iss': email,
}
Node.js 14
// Construct the JWT header.
let jwtHeaders = {
'alg': 'HS256',
'kid': keyID,
}
// Construct the JWT payload.
let jwtPayload = {
'iat': Math.floor(Date.now() / 1000), // current unixtime
'exp': Math.floor(Date.now() / 1000) + 3600, // expiration unixtime
'aud': 'https://identity.disruptive-technologies.com/oauth2/token',
'iss': email,
}
Go 1.16
// Construct the JWT header.
jwtHeader := map[string]interface{}{
"alg": "HS256",
"kid": keyID,
}
// Construct the JWT payload. (Claims in golang)
jwtPayload := &jwt.StandardClaims{
IssuedAt: time.Now().Unix(), // current unixtime
ExpiresAt: time.Now().Add(1 * time.Hour).Unix(), // expiration unixtime
Audience: tokenEndpoint,
Issuer: email,
}

The simplest way of Base64-encoding and signing our JWT is to use some language-specific library. This is available in most languages but can be done manually if desired.

Python 3.9
Node.js 14
Go 1.16
Python 3.9
# Sign and encode JWT with the secret.
encoded_jwt = jwt.encode(
payload = jwt_payload,
key = secret,
algorithm = 'HS256',
headers = jwt_headers,
)
Node.js 14
// Sign and encode JWT with the secret.
const jwtEncoded = jwt.sign(
jwtPayload,
secret,
{
header: jwtHeaders,
algorithm: 'HS256',
},
)
Go 1.16
// Sign and encode JWT with the secret.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwtPayload)
token.Header = jwtHeader
encodedJwt, _ := token.SignedString([]byte(secret))

Exchange for Access Token

The encoded JWT is exchanged for an Access Token by sending a POST request to the same endpoint used to construct the JWT, namely https://identity.disruptive-technologies.com/oauth2/token.

The POST request header should include a Content-Type field indicating the format of the body. Additionally, the POST request body is Form URL-Encoded and contains the following fields:

  1. "assertion" - Contains the encoded JWT string.

  2. "grant_type" - Contains the string "urn:ietf:params:oauth:grant-type:jwt-bearer". This specifies that you want to exchange a JWT for an Access Token.

It is important to note that the data has to be Form URL-Encoded. Like Python's requests, some libraries do this by default and require no further input by the user. This is, however, not the norm and likely requires an additional step before sending the request. The URL Form Encoded data should have the following format.

assertion=Base64Url(header).Base64Url(payload).Base64Url(signature)&grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer

The header, payload, and signature are found in the previous step.

Python 3.9
Node.js 14
Go 1.16
Python 3.9
# Prepare HTTP POST request data.
# Note: The requests package applies Form URL-Encoding by default.
request_data = {
'assertion': encoded_jwt,
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer'
}
# Exchange the JWT for an access token.
access_token_response = requests.post(
url = 'https://identity.disruptive-technologies.com/oauth2/token',
headers = { 'Content-Type': 'application/x-www-form-urlencoded' },
data = request_data,
)
Node.js 14
// Prepare POST request data.
const requestObject = {
'assertion': jwtEncoded,
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
}
// Converts the requestObject to a Form URL-Encoded string.
const requestData = Object.keys(requestObject).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(requestObject[key])
}).join('&')
// Exchange JWT for access token.
const accessTokenResponse = await axios({
method: 'POST',
url: 'https://identity.disruptive-technologies.com/oauth2/token',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: requestData,
}).catch(function (error) {
if (error.response) {
console.log(error.response.data)
}
throw error
})
Go 1.16
// Prepare HTTP POST request data.
// note: Form URL-Encode required and applied with .Encode()
reqData := url.Values{
"assertion": {encodedJwt},
"grant_type": {"urn:ietf:params:oauth:grant-type:jwt-bearer"},
}.Encode()
// Create a new request object.
req, err := http.NewRequest(
"POST",
tokenEndpoint,
strings.NewReader(reqData),
)
if err != nil {
return "", err
}
// Set request headers.
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// Create a client and send the request.
client := &http.Client{Timeout: time.Second * 3}
res, err := client.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()

The access token response can be expected to have the following format. It will be valid for 1 hour only. To refresh the token, perform the previous steps again.

{
"access_token": "d663e83546294b158fea2574a1945319",
"token_type": "bearer",
"expires_in": 3599
}

Access the REST API

Once you have the Access Token, you need to include this with every call to the API. This can be achieved by including the Authorization header in the form shown in the snippet below.

Python 3.9
Node.js 14
Go 1.16
Python 3.9
# Test the token by sending a GET request for a list of projects.
print(requests.get(
url = 'https://api.disruptive-technologies.com/v2/projects',
headers = {'Authorization': 'Bearer ' + access_token},
).json())
Node.js 14
// Test the token by sending a GET request for a list of projects.
const response = await axios({
method: 'GET',
url: 'https://api.disruptive-technologies.com/v2/projects',
headers: { 'Authorization': 'Bearer ' + accessToken },
})
Go 1.16
// Test the access token by listing all projects.
if err := listProjects(accessToken); err != nil {
log.Fatal(err)
}

Next Steps

You are now familiar with the OAuth2 authentication routine, but it must still be refreshed every hour for integrations that run continuously. For this, see our example on Refreshing Access Token.

Common Errors

For an overview of all REST API errors, please see our Error Codes Reference.

  • [400] {'error': 'invalid_grant', 'error_description': 'Signature has expired'} Authentication Error. Your JWT timeframe is invalid. The fields iat, issued at, and exp, expiration time should be now and one hour in the future respectively, both in unixtime.

  • [400] {'error': 'invalid_grant', 'error_description': 'too long expiry'} Authentication Error. Your JWT timeframe is invalid. The fields iat, issued at, and exp, expiration time should be now and one hour in the future respectively, both in unixtime.

  • [400] {'error': 'invalid_grant'} Authentication Error. Might be caused by any of the following reasons:

    • The Service Account may not exist.

    • The Service Account key may not exist.

    • The assertion (encoded JWT) is missing or malformed. Make sure it is Form URL-encoded as described above.

  • [400] {error: 'unsupported_grant_type'} Authentication Error. Might be caused by any of the following reasons:

    • Failure to URL Form Encoding the POST request data when exchanging the JWT for an Access Token. Verify that this step is performed, and if so, correctly.

    • The grant_type field is missing from the POST request body or is malformed (should be Form URL-Encoded).

    • The Content-Type header is not set to application/x-www-form-urlencoded.

  • [403] {error: 'not allowed'} REST API Error. You lack access to support the call you're trying to make. Check that your Service Account has a sufficient Role in the project you wish to authenticate towards.