Generate SAS token for Azure API Management with Node Js.
Published: 2023-07-06 07:44:36


Azure API management is a platform provided by Microsoft Azure that enables organizations to publish, secure, manage, and analyze their APIs. API's allows different software application to communicate and interact with each other. Azure API management simplifies process of creating, maintaining and API deployment process. 

This blog will help you out to generate access token programmatically using node js. This token is used to make direct call to Azure API management REST API. If you want sample code in c# .net then refer this link (https://learn.microsoft.com/en-us/rest/api/apimanagement/apimanagementrest/azure-api-management-rest-api-authentication)

It is possible to create SAS token manually, for that purpose use above url or navigate to Azure Management Portal and generate SAS token from there. 
Login to Portal - Azure API Management Services - Deployment + Infrastructure -- Management API -- generate Token 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/unuvfu1sug7q5fvzq1sa.png)


Mention the expiry date for token in Expiry text box. 
Generate Token Manually Through Code : 
	1. Construct a sign in string in below format - 
		{identifier} + "\n" + {expiry}
		Here, identifier - it’s the identifier field from the API management tab from Azure API management instance. 
		expiry - desired expiry date of SAS token. 
		
		const expiry = new Date();
		expiry.setDate(expiry.getDate() + 10);
		const expiryString = `${expiry.toISOString().split(".")[0]}.${formatMilliseconds(expiry.getMilliseconds())}Z`;
		const encoder = crypto.createHmac("sha512",Buffer.from(AZ_APIM_KEY, "utf8"));
		
(AZ_APIM_KEY - Used API Key as constant - you please use your own key from Azure)

	2. Need to generate a signature by applying HMAC-SHA512 hash function to sign in string using key. Base 64 encode returned signature key.
	
		    const dataToSign = `integration\n${expiryString}`;
		    const dataToSignBytes = encoder.update(dataToSign, "utf8").digest();
		    const signature = dataToSignBytes.toString("base64");
	
	3. Finally created access token in below format.
		a. uid= {identifier}&ex={expiry}&sn={Base64 encoded signature format}
		
	e.g. Token generated here is with above example -
	
Token = `SharedAccessSignature uid=${AZ_APIM_IDENTIFIER}&ex=${expiryString}&sn=${signature}`;

**Following is full code of token generation using node js -**
	
	const createToken = async () => {
	  try {
	    const expiry = new Date();
	    expiry.setDate(expiry.getDate() + 10);
	
	    const expiryString = `${expiry.toISOString().split(".")[0]}.${formatMilliseconds(expiry.getMilliseconds())}Z`;
	    const encoder = crypto.createHmac("sha512",Buffer.from(AZ_APIM_KEY, "utf8"));
	
	    const dataToSign = `${AZ_APIM_IDENTIFIER}\n${expiryString}`;
	    const dataToSignBytes = encoder.update(dataToSign, "utf8").digest();
	    const signature = dataToSignBytes.toString("base64");
	
	    const token = `SharedAccessSignature uid=${AZ_APIM_IDENTIFIER}&ex=${expiryString}&sn=${signature}`;
	    return token;
	
	  } catch (error:any) {
	    console.log(error);
	    logs.insertLog(new Date(), "Error", "Crosswalk", "Expiration Utility", "1.0", "createToken", error.exceptionType, "Error observed while creating token", error.message, "", error.source, error.stackTrace);
	  }
	};
	
Use this access token as an Authorization key for further API call in Azure API management to change the subscription status/Subscriber status etc. depend on requirement. Refer below url for update user or subscription.
https://learn.microsoft.com/en-us/rest/api/apimanagement/current-ga/user/update?tabs=HTTP

	const url = `${baseURL}/subscriptions/{Your details for url}`;
	
 base url - here baseURL is constant - construct your base url based on API management url subscription or subscription id resource group etc 

	    const payload = {
	      properties: {
	        state: `expired`,
	      },
	    };
	    const token = await createToken();
	    const response = await axios.patch(url, payload, {
	      headers: {
	        Authorization: `${token}`,
	        "content-type": "application/json",
	      },
	    });
	
Execute above call to make changes at Azure API management.