Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate an azure blob url with SAS signature in nodejs sdk v12?

previously (in older sdk like v2) you can generate a sas url (a signed shareable url for a blob) like following :

var azure = require('azure-storage');
var blobService = azure.createBlobService();

var startDate = new Date();
var expiryDate = new Date(startDate);
expiryDate.setMinutes(startDate.getMinutes() + 100);
startDate.setMinutes(startDate.getMinutes() - 100);

var sharedAccessPolicy = {
  AccessPolicy: {
    Permissions: azure.BlobUtilities.SharedAccessPermissions.READ,
    Start: startDate,
    Expiry: expiryDate
  }
};

var token = blobService.generateSharedAccessSignature(containerName, blobName, sharedAccessPolicy);
var sasUrl = blobService.getUrl(containerName, blobName, token);

I'm wondering how we can generate that url in sdk v12? I could not find any documentation for Sas URL in v12.

BlobUtilities and getUrl() methods also not available in v12 (in v12 there are separate packages for every module , in my case I'm using require("@azure/storage-blob");)

Thanks.

like image 281
HasanKeyf Avatar asked Dec 07 '22 10:12

HasanKeyf


1 Answers

Regarding the issue, please refer to the following code

var storage = require("@azure/storage-blob")
  const accountname ="blobstorage0516";
    const key = "";
    const cerds = new storage.StorageSharedKeyCredential(accountname,key);
    const blobServiceClient = new storage.BlobServiceClient(`https://${accountname}.blob.core.windows.net`,cerds);
    const containerName="test";
    const client =blobServiceClient.getContainerClient(containerName)
    const blobName="help.txt";
    const blobClient = client.getBlobClient(blobName);

    const blobSAS = storage.generateBlobSASQueryParameters({
      containerName, 
      blobName, 
      permissions: storage.BlobSASPermissions.parse("racwd"), 
      startsOn: new Date(),
      expiresOn: new Date(new Date().valueOf() + 86400)
    },
    cerds 
  ).toString();

    const sasUrl= blobClient.url+"?"+blobSAS;
    console.log(sasUrl);

enter image description here

like image 74
Jim Xu Avatar answered Dec 11 '22 10:12

Jim Xu