Node js – Azure blob storage generate temporary public url for private file.

This article demonstrates how to generate a temporary public URL to access a private file which resides inside the Azure blob storage which has private access.

We gonna use NodeJS and Azure’s official npm module to generate a temporary public URL for a private file using shared access signatures (SAS).

Let’s create a directory called AzureBlogTest and Initiate the project with,npm init --yes it will create a file namedpackage.json inside the current directory. Now install the project dependency with npm install azure-storage

After installing decency, let’s create a file namedserver.js and place below code in it.

const azureStorage = require('azure-storage');
const blobService = azureStorage.createBlobService('Azure Account Name','Azure Storage accountKey');

const getBlobTempPublicUrl = (containerName, blobName) => {

    const startDate = new Date();
    const expiryDate = new Date(startDate);
    expiryDate.setMinutes(startDate.getMinutes() + 100);
    startDate.setMinutes(startDate.getMinutes() - 100);
    
    const sharedAccessPolicy = {
        AccessPolicy: {
            Permissions: azureStorage.BlobUtilities.SharedAccessPermissions.READ,
            Start: startDate,
            Expiry: expiryDate
        }
    };
    
    const token = blobService.generateSharedAccessSignature(containerName, blobName, sharedAccessPolicy);
    
    return blobService.getUrl(containerName, blobName, token);
}

const containerName = 'your container name';
const blobName = 'your blob name';

const url = getBlobTempPublicUrl(containerName, blobName);
console.log(url);

Now run the code with node server.js command, in the console you will get Azure Blob URL.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

DMCA.com Protection Status