แก้ไข

แชร์ผ่าน


Create and use account SAS tokens with Azure Blob Storage and JavaScript

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

Account SAS tokens

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:

  • Services: blob, file, queue, table
  • Resource types: service, container, or object
  • Permissions such as create, read, write, update, and delete

Add required dependencies to your application

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()

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.

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
);

Async operation boilerplate

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}`)
    });

Create SAS token

Because this token can be used with blobs, queues, tables, and files, some of the settings are more broad than just blob options.

  1. 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:

  2. 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}`;
    }
    
  3. Secure the SAS token until it is used.

Use Blob service with account 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.

// 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.

See also