DEV Community

Posted on • Originally published at

Generate a Azure SAS token

Azure Documentation

After you've created a Shared Access Policy (SAP) you will need to generate the token to use when send API calls.

We can generate these ourselves, and luckily, Microsoft provides some code for us (see documentation above). Below is a small node script using this code to make life easy.

const crypto = require("crypto")

// In seconds - week
const EXPIRES_IN = 60*60*24*7;

function createSharedAccessToken(uri, saName, saKey) { 
    if (!uri || !saName || !saKey) { 
          throw "Missing required parameter"; 
    var encoded = encodeURIComponent(uri); 
    var now = new Date();
    var ttl = Math.round(now.getTime() / 1000) + EXPIRES_IN;
    var signature = encoded + '\n' + ttl; 
    var hash = crypto.createHmac('sha256', saKey).update(signature, 'utf8').digest('base64'); 
    return 'SharedAccessSignature sr=' + encoded + '&sig=' + encodeURIComponent(hash) + '&se=' + ttl + '&skn=' + saName; 

const uri = "" // Endpoint
const saName = "" // SAP Name
const saKey  = "" // Primary or Secondary Key

    createSharedAccessToken(uri, saName, saKey)
Enter fullscreen mode Exit fullscreen mode

From what I can tell, there isn't a max for the EXPIRES_IN variable. So if you want something that never expires, you can set it to 1000 years.

You'll need to fill in those 3 variables based on your project and then run. node <filename>.js

That will spit out a value that you set the Authorization header to whenever you send a message to your Queue/Topic/etc.

If you don't want to use the node script or you want to read more about this, the documentation as always is your friend.

✌️ Peace!

Top comments (0)