Last active
December 25, 2022 19:54
-
-
Save kevboutin/304abc603106ceee35f74b913249914b to your computer and use it in GitHub Desktop.
Generates a SAS token URL for a particular file in an Azure storage account
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { | |
BlobSASPermissions, generateBlobSASQueryParameters, StorageSharedKeyCredential, | |
} = require('@azure/storage-blob'); | |
/** | |
* Generate a secure token URL for a particular file in a storage account. | |
* | |
* @param {string} accountName The name of the storage account. | |
* @param {string} accountKey The account key. | |
* @param {string} container The container. | |
* @param {string} blobName The file name. | |
* @param {string} permissions The permissions granted by the secure token. | |
* @param {integer} ttl The number of minutes that the token should remain valid. | |
* @returns {object} Contains the SAS token and the URL. | |
*/ | |
const generateSecureTokenUrl = async (accountName, accountKey, container, blobName, permissions = 'r', ttl = 60) => { | |
// Create a SAS token that expires in an hour | |
// Set start time to fifteen minutes ago to avoid clock skew. | |
// This is recommended by Azure. | |
const startDate = new Date(); | |
startDate.setMinutes(startDate.getMinutes() - 15); | |
const expiryDate = new Date(startDate); | |
expiryDate.setMinutes(startDate.getMinutes() + ttl); | |
const sharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey); | |
const sas = generateBlobSASQueryParameters({ | |
containerName: container, | |
blobName, | |
permissions: BlobSASPermissions.parse(permissions), | |
startsOn: startDate, | |
expiresOn: expiryDate, | |
version: '2019-12-12', | |
}, sharedKeyCredential).toString(); | |
const { url } = this.blobServiceClient.getContainerClient(container).getBlockBlobClient(blobName); | |
return { | |
token: sas, | |
url: `${url}?${sas}`, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment