Create and use account SAS tokens with Azure Blob Storage and JavaScript
Article
08/05/2024
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.
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.
Get environment variables to create shared key credential
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.
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.
// Azure Storage dependency
const {
ContainerClient
} = require("@azure/storage-blob");
// For development environment - include environment variables
require("dotenv").config();
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error("Azure Storage accountName not found");
// Container must exist prior to running this script
const containerName = `test`;
// SAS token must have LIST permissions on container that haven't expired
const sasToken = process.env.AZURE_STORAGE_SAS_TOKEN;
// Create SAS URL
const sasUrl = `https://${accountName}.blob.core.windows.net/${containerName}?${sasToken}`;
async function main() {
try {
// create container client from SAS token
const containerClient = new ContainerClient(sasUrl);
// do something with containerClient...
let i = 1;
// List blobs in container
for await (const blob of containerClient.listBlobsFlat()) {
console.log(`Blob ${i++}: ${blob.name}`);
}
} catch (err) {
console.log(err);
throw err;
}
}
main()
.then(() => console.log(`done`))
.catch((ex) => console.log(ex.message));
// Azure Storage dependency
const { BlockBlobClient } = require("@azure/storage-blob");
// For development environment - include environment variables
require("dotenv").config();
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error("Azure Storage accountName not found");
// Container and blob must exist prior to running this script
// SAS token must have READ permissions on blob that haven't expired
const containerName = `test`;
const blobName = `my-text-file.txt`;
// Create SAS URL
const sasToken = process.env.AZURE_STORAGE_SAS_TOKEN;
const sasUrl = `https://${accountName}.blob.core.windows.net/${containerName}/${blobName}?${sasToken}`;
// Utility function to convert a Node.js Readable stream into a Buffer
async function streamToBuffer(readableStream) {
return new Promise((resolve, reject) => {
const chunks = [];
readableStream.on('data', (data) => {
chunks.push(data instanceof Buffer ? data : Buffer.from(data));
});
readableStream.on('end', () => {
resolve(Buffer.concat(chunks));
});
readableStream.on('error', reject);
});
}
async function main(){
// Create a blob client from SAS token
const client = new BlockBlobClient(sasUrl);
// Get blob url
console.log(`blob.url: ${client.url}`);
// Download file contents
const result = await client.download();
const content = await streamToBuffer(result.readableStreamBody);
// Get results
return content.toString();
}
main().then((result) => console.log(result)).catch((ex) => console.log(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.
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.