Generating SAS Tokens

Prerequisites

To use Shared Access Signature tokens as authorization method, create a new HTTP device connector and select the device authentication Shared Access Signature.

Setup a new device with the data flow and copy the deviceId, the primary signing key and use it in the following code example to generate a token.

Generating tokens

import crypto from "crypto";
import axios from "axios";

const generateSasToken = (
  signingKey,
  resourceUri,
  expiryInSeconds,
  deviceConnectorIdAudience,
  deviceIdAudience
) => {
  let query = `deviceConnectorIdAudience=${deviceConnectorIdAudience}\n`;
  if (deviceIdAudience !== null) {
    query += `deviceIdAudience=${deviceIdAudience}\n`;
  }
  query += `expiry=${expiryInSeconds}`;
  const encodedQuery = encodeURIComponent(query);

  let hmac = crypto.createHmac("sha256", Buffer.from(signingKey, "base64url"));
  hmac.update(encodedQuery);

  let signature = encodeURIComponent(hmac.digest("base64"));
  let token = `sig=${signature}&exp=${expiryInSeconds}&aud=${encodeURIComponent(
    resourceUri
  )}`;
  return Buffer.from(token).toString("base64");
};

// generate the token
const baseUrl = "https://data-gateway.akenza.io"
const expiry = Math.ceil(Date.now() / 1000 + 60 * 60 * 24); // 1d
const signingKey = "<primaryOrSecondarySigningKey>";
const deviceConnectorId = "<yourDeviceConnectorId>";
const deviceId = "<yourPhysicalDEviceId>";
const resourceUri = `https://akenza.io/device-connectors/${deviceConnectorId}/devices/${deviceId}`;
const token = generateSasToken(
    signingKey,
    resourceUri,
    expiry,
    deviceConnectorId,
    deviceId
  );
  
// send the uplink
const url = `${baseUrl}/v3/capture?deviceId=${deviceId}&topic=default`;
const options = {
    headers: {
      "Content-Type": "application/json",
      "x-access-signature": token,
    },
  };
const body = { param1: "value" };
const response = await axios.post(url, body, options);

Last updated

Was this helpful?