Events
31 Mar, 11 pm - 2 Apr, 11 pm
The biggest Fabric, Power BI, and SQL learning event. March 31 – April 2. Use code FABINSIDER to save $400.
Register todayThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
This article shows you how to create and use account SAS tokens to use the Azure Blob Storage client library v12 for JavaScript. Once connected, your code can operate on containers, blobs, and features of the Blob Storage service.
The sample code snippets are available in GitHub as runnable Node.js files.
Package (npm) | Samples | API reference | Library source code | Give Feedback
An account SAS token is one type of SAS token for access delegation provided by Azure Storage. An account SAS token provides access to Azure Storage. The token is only as restrictive as you define it when creating it. Because anyone with the token can use it to access your Storage account, you should define the token with the most restrictive permissions that still allow the token to complete the required tasks.
Best practices for token creation include limiting permissions:
Include the required dependencies to create an account SAS token.
const {
BlobServiceClient,
generateAccountSASQueryParameters,
AccountSASPermissions,
AccountSASServices,
AccountSASResourceTypes,
StorageSharedKeyCredential,
SASProtocol
} = require('@azure/storage-blob');
require('dotenv').config()
Use the Blob Storage account name and key to create a StorageSharedKeyCredential. This key is required to create the SAS token and to use the SAS token.
Create a StorageSharedKeyCredential by using the storage account name and account key. Then use the StorageSharedKeyCredential to initialize a BlobServiceClient.
const constants = {
accountName: process.env.AZURE_STORAGE_ACCOUNT_NAME,
accountKey: process.env.AZURE_STORAGE_ACCOUNT_KEY
};
const sharedKeyCredential = new StorageSharedKeyCredential(
constants.accountName,
constants.accountKey
);
The remaining sample code snippets assume the following async boilerplate code for Node.js.
async function main() {
const sasToken = await createAccountSas();
await useSasToken(sasToken);
}
main()
.then(() => {
console.log(`done`);
}).catch((ex) => {
console.log(`Error: ${ex.message}`)
});
Because this token can be used with blobs, queues, tables, and files, some of the settings are more broad than just blob options.
Create the options object.
The scope of the abilities of a SAS token is defined by the AccountSASSignatureValues.
Use the following helper functions provided by the SDK to create the correct value types for the values:
Pass the object to the generateAccountSASQueryParameters function, along with the SharedKeyCredential, to create the SAS token.
Before returning the SAS token, prepend the query string delimiter, ?
.
async function createAccountSas() {
const sasOptions = {
services: AccountSASServices.parse("btqf").toString(), // blobs, tables, queues, files
resourceTypes: AccountSASResourceTypes.parse("sco").toString(), // service, container, object
permissions: AccountSASPermissions.parse("rwdlacupi"), // permissions
protocol: SASProtocol.Https,
startsOn: new Date(),
expiresOn: new Date(new Date().valueOf() + (10 * 60 * 1000)), // 10 minutes
};
const sasToken = generateAccountSASQueryParameters(
sasOptions,
sharedKeyCredential
).toString();
console.log(`sasToken = '${sasToken}'\n`);
// prepend sasToken with `?`
return (sasToken[0] === '?') ? sasToken : `?${sasToken}`;
}
Secure the SAS token until it is used.
To use the account SAS token, you need to combine it with the account name to create the URI. Pass the URI to create the blobServiceClient. Once you have the blobServiceClient, you can use that client to access your Blob service.
// connect-with-sas-token.js
const { BlobServiceClient } = require('@azure/storage-blob');
require('dotenv').config()
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
const sasToken = process.env.AZURE_STORAGE_SAS_TOKEN;
if (!accountName) throw Error('Azure Storage accountName not found');
if (!sasToken) throw Error('Azure Storage accountKey not found');
const blobServiceUri = `https://${accountName}.blob.core.windows.net`;
// https://YOUR-RESOURCE-NAME.blob.core.windows.net?YOUR-SAS-TOKEN
const blobServiceClient = new BlobServiceClient(
`${blobServiceUri}?${sasToken}`,
null
);
async function main(){
const containerName = 'REPLACE-WITH-EXISTING-CONTAINER-NAME';
const blobName = 'REPLACE-WITH-EXISTING-BLOB-NAME';
const timestamp = Date.now();
const fileName = `my-new-file-${timestamp}.txt`;
// create container client
const containerClient = await blobServiceClient.getContainerClient(containerName);
// create blob client
const blobClient = await containerClient.getBlockBlobClient(blobName);
// download file
await blobClient.downloadToFile(fileName);
console.log(`${fileName} downloaded`);
}
main()
.then(() => console.log(`done`))
.catch((ex) => console.log(`error: ${ex.message}`));
The dotenv
package is used to read your storage account name from a .env
file. This file should not be checked into source control.
Events
31 Mar, 11 pm - 2 Apr, 11 pm
The biggest Fabric, Power BI, and SQL learning event. March 31 – April 2. Use code FABINSIDER to save $400.
Register todayTraining
Module
Upload images to Azure Blob Storage from a static web app - Training
Learn how to securely upload images to Azure Blob Storage from a static web app by using an Azure Function to generate on demand shared access signatures.
Certification
Microsoft Certified: Azure Developer Associate - Certifications
Build end-to-end solutions in Microsoft Azure to create Azure Functions, implement and manage web apps, develop solutions utilizing Azure storage, and more.