In Azure APIM Management API, how to programmatically create a SAS token?

Chirag Chhajed 0 Reputation points
2024-03-13T12:54:35.79+00:00

User's image

I am trying to automate the process of access token generation. https://learn.microsoft.com/en-us/rest/api/apimanagement/apimanagementrest/azure-api-management-rest-api-authentication?view=rest-apimanagement-2022-08-01 in this article, the code sample uses C# but I am using nodejs. Token generated from azure portal works but token generated from this function gives a 401 Unauthorized error.

I want to access token for using this api https://learn.microsoft.com/en-us/rest/api/apimanagement/user/get-shared-access-token?view=rest-apimanagement-2022-08-01&tabs=HTTP

code in nodejs:

import crypto from "crypto";

const generateSasToken = (id: string, key: string, expiry: Date): string => {
  const stringToSign = `${id}\n${expiry.toISOString()}`;
  const signature = crypto
    .createHmac("sha512", Buffer.from(key, "base64"))
    .update(stringToSign)
    .digest("base64");

  return `SharedAccessSignature uid=${id}&ex=${expiry.toISOString().replace(/\.\d+Z$/, ".0000000Z")}&sn=${signature}`;
};

export { generateSasToken };

console.log(
  generateSasToken(
    "integration",
    "n6kzqtxmNF8C15QErUyiSOOD1bEq91dD75QCtAblHObn4wkyJN4+uCnENyk2XYTnEwfXNOJWqdQD2+cj5PU+cA==",
    new Date(Date.now() + 10 * 24 * 60 * 60 * 1000)
  )
);

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
1,959 questions
{count} votes