In dit artikel leest u hoe u verbinding maakt met Azure Blob Storage met behulp van de Azure Blob Storage-clientbibliotheek voor JavaScript. Zodra de code is verbonden, kan uw code worden uitgevoerd op containers, blobs en functies van de Blob Storage-service.
Voor clienttoepassingen (browsertoepassingen) hebt u bundelprogramma's nodig.
Uw project instellen
Open een opdrachtprompt en ga naar de projectmap. Ga naar YOUR-DIRECTORY de mapnaam:
cd YOUR-DIRECTORY
Als u nog geen bestand in uw map hebt package.json , initialiseert u het project om het bestand te maken:
npm init -y
Installeer TypeScript en de Azure Blob Storage-clientbibliotheek voor JavaScript met typeScript-typen:
npm install typescript @azure/storage-blob
Als u wachtwoordloze verbindingen wilt gebruiken met behulp van Microsoft Entra ID, installeert u de Azure Identity-clientbibliotheek voor JavaScript:
npm install @azure/identity
Toegang autoriseren en verbinding maken met Blob Storage
Microsoft Entra ID biedt de veiligste verbinding door de verbindingsidentiteit (beheerde identiteit) te beheren. Met deze functionaliteit zonder wachtwoord kunt u een toepassing ontwikkelen waarvoor geen geheimen (sleutels of verbindingsreeks s) zijn vereist die zijn opgeslagen in de code.
Identiteitstoegang tot de Azure-cloud instellen
Als u zonder wachtwoorden verbinding wilt maken met Azure, moet u een Azure-identiteit instellen of een bestaande identiteit gebruiken. Zodra de identiteit is ingesteld, moet u de juiste rollen toewijzen aan de identiteit.
Als u toegang zonder wachtwoord wilt autoriseren met Microsoft Entra ID, moet u een Azure-referentie gebruiken. Welk type referentie u nodig hebt, is afhankelijk van waar uw toepassing wordt uitgevoerd. Gebruik deze tabel als richtlijn.
Voor uw opslagresource moeten een of meer van de volgende Azure RBAC-rollen zijn toegewezen aan de identiteitsresource waarmee u verbinding wilt maken. Stel de Azure Storage-rollen in voor elke identiteit die u in de vorige stap hebt gemaakt: Azure-cloud, lokale ontwikkeling, on-premises.
Nadat u de installatie hebt voltooid, heeft elke identiteit ten minste één van de juiste rollen nodig:
Zodra uw Azure Storage-account-id-rollen en uw lokale omgeving zijn ingesteld, maakt u een TypeScript-bestand dat het @azure/identity pakket bevat. Maak een referentie, zoals defaultAzureCredential, om wachtwoordloze verbindingen met Blob Storage te implementeren. Gebruik deze referentie om te verifiëren met een BlobServiceClient-object .
// connect-with-default-azure-credential.js
// You must set up RBAC for your identity with one of the following roles:
// - Storage Blob Data Reader
// - Storage Blob Data Contributor
import { DefaultAzureCredential } from '@azure/identity';
import { BlobServiceClient } from '@azure/storage-blob';
import * as dotenv from 'dotenv';
dotenv.config();
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME as string;
if (!accountName) throw Error('Azure Storage accountName not found');
const blobServiceClient = new BlobServiceClient(
`https://${accountName}.blob.core.windows.net`,
new DefaultAzureCredential()
);
async function main() {
const containerName = 'my-container';
const blobName = 'my-blob';
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
const downloadResult = await blobClient.downloadToFile(fileName);
if (downloadResult.errorCode) throw Error(downloadResult.errorCode);
console.log(
`${fileName} downloaded ${downloadResult.contentType}, isCurrentVersion: ${downloadResult.isCurrentVersion}`
);
}
main()
.then(() => console.log(`success`))
.catch((err: unknown) => {
if (err instanceof Error) {
console.log(err.message);
}
});
Het dotenv pakket wordt gebruikt om de naam van uw opslagaccount uit een .env bestand te lezen. Dit bestand mag niet worden ingecheckt bij broncodebeheer. Als u een lokale service-principal gebruikt als onderdeel van uw DefaultAzureCredential-configuratie, gaan alle beveiligingsgegevens voor die referentie ook naar het .env bestand.
Als u van plan bent om de toepassing te implementeren op servers en clients die buiten Azure worden uitgevoerd, maakt u een van de referenties die aan uw behoeften voldoen.
// connect-with-account-name-and-key.js
import {
BlobServiceClient,
StorageSharedKeyCredential
} from '@azure/storage-blob';
import * as dotenv from 'dotenv';
import path from 'path';
dotenv.config();
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME as string;
const accountKey = process.env.AZURE_STORAGE_ACCOUNT_KEY as string;
if (!accountName) throw Error('Azure Storage accountName not found');
if (!accountKey) throw Error('Azure Storage accountKey not found');
const sharedKeyCredential = new StorageSharedKeyCredential(
accountName,
accountKey
);
const blobServiceClient = new BlobServiceClient(
`https://${accountName}.blob.core.windows.net`,
sharedKeyCredential
);
async function main(): Promise<void> {
const containerName = 'my-container';
const blobName = 'my-blob';
const timestamp = Date.now();
const fileName = path.join(
__dirname,
'../files',
`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
const downloadResult = await blobClient.downloadToFile(fileName);
if (downloadResult.errorCode) throw Error(downloadResult.errorCode);
console.log(
`${fileName} downloaded, created on ${downloadResult.createdOn}}`
);
}
main()
.then(() => console.log(`success`))
.catch((err: unknown) => {
if (err instanceof Error) {
console.log(err.message);
}
});
Het dotenv pakket wordt gebruikt om de naam en sleutel van uw opslagaccount uit een .env bestand te lezen. Dit bestand mag niet worden ingecheckt bij broncodebeheer.
Zie Toegangssleutels voor opslagaccounts beheren voor informatie over het verkrijgen van accountsleutels en aanbevolen procedures voor het correct beheren en beveiligen van uw sleutels.
Belangrijk
De toegangssleutel voor het account moet voorzichtig worden gebruikt. Als uw accounttoegangssleutel verloren gaat of per ongeluk op een onveilige locatie is geplaatst, kan uw service kwetsbaar worden. Iedereen met de toegangssleutel kan aanvragen voor het opslagaccount autoriseren en heeft effectief toegang tot alle gegevens. DefaultAzureCredential biedt verbeterde beveiligingsfuncties en voordelen en is de aanbevolen benadering voor het beheren van autorisatie voor Azure-services.
Maak een URI voor uw resource met behulp van het blob-service-eindpunt en het SAS-token. Maak vervolgens een BlobServiceClient met de Uri. Het SAS-token is een reeks naam-/waardeparen in de querytekenreeks in de indeling, zoals:
Afhankelijk van het hulpprogramma dat u gebruikt om uw SAS-token te genereren, kan de querystring ? al worden toegevoegd aan het SAS-token.
// connect-with-sas-token.js
import { BlobServiceClient } from '@azure/storage-blob';
import * as dotenv from 'dotenv';
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');
// https://YOUR-RESOURCE-NAME.blob.core.windows.net?YOUR-SAS-TOKEN
const blobServiceUri = `https://${accountName}.blob.core.windows.net?${sasToken}`;
// SAS tokens do not require an additional credential because
// the token is the credential
const credential = undefined;
const blobServiceClient = new BlobServiceClient(blobServiceUri, credential);
async function main() {
const containerName = 'my-container';
const blobName = 'my-blob';
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
const downloadResult = await blobClient.downloadToFile(fileName);
if (downloadResult.errorCode) throw Error(downloadResult.errorCode);
console.log(
`${fileName} downloaded ${downloadResult.contentType}, isCurrentVersion: ${downloadResult.isCurrentVersion}`
);
}
main()
.then(() => console.log(`success`))
.catch((err: unknown) => {
if (err instanceof Error) {
console.log(err.message);
}
});
Het dotenv pakket wordt gebruikt om de naam en het SAS-token van uw opslagaccount uit een .env bestand te lezen. Dit bestand mag niet worden ingecheckt bij broncodebeheer.
Als u SAS-tokens wilt genereren en beheren, raadpleegt u een van de volgende artikelen:
Voor scenario's waarin SHARED Access Signatures (SAS) worden gebruikt, raadt Microsoft aan een SAS voor gebruikersdelegering te gebruiken. Een SAS voor gebruikersdelegering wordt beveiligd met Microsoft Entra-referenties in plaats van de accountsleutel. Zie Een SAS voor gebruikersdelegatie maken met JavaScript voor meer informatie.
// Azure Storage dependency
import { ContainerClient } from '@azure/storage-blob';
// Azure authentication for credential dependency
import { DefaultAzureCredential } from '@azure/identity';
// For development environment - include environment variables from .env
import * as dotenv from 'dotenv';
dotenv.config();
// Azure Storage resource name
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME as string;
if (!accountName) throw Error('Azure Storage accountName not found');
// Azure SDK needs base URL
const baseUrl = `https://${accountName}.blob.core.windows.net`;
// Unique container name
const timeStamp = Date.now();
const containerName = `my-container`;
async function main(): Promise<void> {
try {
// create container client from DefaultAzureCredential
const containerClient = new ContainerClient(
`${baseUrl}/${containerName}`,
new DefaultAzureCredential()
);
// do something with containerClient...
let i = 1;
// List blobs in container
for await (const blob of containerClient.listBlobsFlat({
includeMetadata: true,
includeSnapshots: false,
includeTags: true,
includeVersions: false,
prefix: ''
})) {
console.log(`Blob ${i++}: ${blob.name}`);
}
} catch (err) {
console.log(err);
throw err;
}
}
main()
.then(() => console.log(`success`))
.catch((err: unknown) => {
if (err instanceof Error) {
console.log(err.message);
}
});
// Azure Storage dependency
import {
ContainerClient,
StorageSharedKeyCredential
} from '@azure/storage-blob';
// For development environment - include environment variables from .env
import * as dotenv from 'dotenv';
dotenv.config();
// Azure Storage resource name
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME as string;
if (!accountName) throw Error('Azure Storage accountName not found');
// Azure Storage resource key
const accountKey = process.env.AZURE_STORAGE_ACCOUNT_KEY as string;
if (!accountKey) throw Error('Azure Storage accountKey not found');
const sharedKeyCredential = new StorageSharedKeyCredential(
accountName,
accountKey
);
const baseUrl = `https://${accountName}.blob.core.windows.net`;
const containerName = `my-container`;
async function main(): Promise<void> {
try {
// create container from ContainerClient
const containerClient = new ContainerClient(
`${baseUrl}/${containerName}`,
sharedKeyCredential
);
// do something with containerClient...
let i = 1;
// List blobs in container
for await (const blob of containerClient.listBlobsFlat({
includeMetadata: true,
includeSnapshots: false,
includeTags: true,
includeVersions: false,
prefix: ''
})) {
console.log(`Blob ${i++}: ${blob.name}`);
}
} catch (err) {
console.log(err);
throw err;
}
}
main()
.then(() => console.log(`success`))
.catch((err: unknown) => {
if (err instanceof Error) {
console.log(err.message);
}
});
Belangrijk
De toegangssleutel voor het account moet voorzichtig worden gebruikt. Als uw accounttoegangssleutel verloren gaat of per ongeluk op een onveilige locatie is geplaatst, kan uw service kwetsbaar worden. Iedereen met de toegangssleutel kan aanvragen voor het opslagaccount autoriseren en heeft effectief toegang tot alle gegevens. DefaultAzureCredential biedt verbeterde beveiligingsfuncties en voordelen en is de aanbevolen benadering voor het beheren van autorisatie voor Azure-services.
// Azure Storage dependency
import { ContainerClient } from '@azure/storage-blob';
// For development environment - include environment variables
import * as dotenv from 'dotenv';
dotenv.config();
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME as string;
if (!accountName) throw Error('Azure Storage accountName not found');
// Container must exist prior to running this script
const containerName = `my-container`;
// SAS token must have LIST permissions on container that haven't expired
const sasToken = process.env.AZURE_STORAGE_SAS_TOKEN as string;
// Create SAS URL
const sasUrl = `https://${accountName}.blob.core.windows.net/${containerName}?${sasToken}`;
async function main(): Promise<void> {
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({
includeMetadata: true,
includeSnapshots: false,
includeTags: true,
includeVersions: false,
prefix: ''
})) {
console.log(`Blob ${i++}: ${blob.name}`);
}
} catch (err) {
console.log(err);
throw err;
}
}
main()
.then(() => console.log(`success`))
.catch((err: unknown) => {
if (err instanceof Error) {
console.log(err.message);
}
});
Notitie
Voor scenario's waarin SHARED Access Signatures (SAS) worden gebruikt, raadt Microsoft aan een SAS voor gebruikersdelegering te gebruiken. Een SAS voor gebruikersdelegering wordt beveiligd met Microsoft Entra-referenties in plaats van de accountsleutel. Zie Een SAS voor gebruikersdelegatie maken met JavaScript voor meer informatie.
Het dotenv pakket wordt gebruikt om de naam van uw opslagaccount uit een .env bestand te lezen. Dit bestand mag niet worden ingecheckt bij broncodebeheer.
Een BlobClient-object maken
U kunt een van de Onderstaande BlobClient-objecten maken, hetzij vanuit een ContainerClient, hetzij rechtstreeks.
// Azure Storage dependency
import {
BlockBlobClient,
BlockBlobUploadHeaders,
BlockBlobUploadResponse
} from '@azure/storage-blob';
import { getBlockBlobClientFromDefaultAzureCredential } from './auth-get-client';
// For development environment - include environment variables from .env
import * as dotenv from 'dotenv';
dotenv.config();
// Container must exist prior to running this script
const containerName = `my-container`;
// Random blob name and contents
const timeStamp = Date.now();
const blobName = `${timeStamp}-my-blob.txt`;
const fileContentsAsString = 'Hello there.';
const blockBlobClient: BlockBlobClient =
getBlockBlobClientFromDefaultAzureCredential(containerName, blobName);
async function main(
blockBlobClient: BlockBlobClient
): Promise<BlockBlobUploadHeaders> {
// Get file url - available before contents are uploaded
console.log(`blob.url: ${blockBlobClient.url}`);
// Upload file contents
const result: BlockBlobUploadHeaders = await blockBlobClient.upload(
fileContentsAsString,
fileContentsAsString.length
);
if (result.errorCode) throw Error(result.errorCode);
// Get results
return result;
}
main(blockBlobClient)
.then((result) => {
console.log(result);
console.log(`success`);
})
.catch((err: unknown) => {
if (err instanceof Error) {
console.log(err.message);
}
});
/*
Response looks like this:
{
etag: '"0x8DAD247F1F4896E"',
lastModified: 2022-11-29T20:26:07.000Z,
contentMD5: <Buffer 9d 6a 29 63 87 20 77 db 67 4a 27 a3 9c 49 2e 61>,
clientRequestId: 'a07fdd1f-5937-44c7-984f-0699a48a05c0',
requestId: '3580e726-201e-0045-1a30-0474f6000000',
version: '2021-04-10',
date: 2022-11-29T20:26:06.000Z,
isServerEncrypted: true,
'content-length': '0',
server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-content-crc64': 'BLv7vb1ONT8=',
body: undefined
}
*/
// Azure Storage dependency
import {
BlockBlobClient,
BlockBlobUploadHeaders,
BlockBlobUploadResponse,
StorageSharedKeyCredential
} from '@azure/storage-blob';
// For development environment - include environment variables from .env
import * as dotenv from 'dotenv';
dotenv.config();
// Azure Storage resource name
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME as string;
if (!accountName) throw Error('Azure Storage accountName not found');
// Azure Storage resource key
const accountKey = process.env.AZURE_STORAGE_ACCOUNT_KEY as string;
if (!accountKey) throw Error('Azure Storage accountKey not found');
// Create credential
const sharedKeyCredential: StorageSharedKeyCredential =
new StorageSharedKeyCredential(accountName, accountKey);
const baseUrl = `https://${accountName}.blob.core.windows.net`;
const containerName = `my-container`;
const blobName = `my-blob`;
const fileContentsAsString = 'Hello there.';
async function main(): Promise<void> {
try {
// create blob from BlockBlobClient
const blockBlobClient = new BlockBlobClient(
`${baseUrl}/${containerName}/${blobName}`,
sharedKeyCredential
);
// Upload data to the blob
const blockBlobUploadResponse: BlockBlobUploadHeaders =
await blockBlobClient.upload(
fileContentsAsString,
fileContentsAsString.length
);
if (blockBlobUploadResponse.errorCode)
throw Error(blockBlobUploadResponse.errorCode);
console.log(`blob ${blockBlobClient.url} created`);
} catch (err) {
console.log(err);
throw err;
}
}
main()
.then(() => console.log(`success`))
.catch((err: unknown) => {
if (err instanceof Error) {
console.log(err.message);
}
});
Belangrijk
De toegangssleutel voor het account moet voorzichtig worden gebruikt. Als uw accounttoegangssleutel verloren gaat of per ongeluk op een onveilige locatie is geplaatst, kan uw service kwetsbaar worden. Iedereen met de toegangssleutel kan aanvragen voor het opslagaccount autoriseren en heeft effectief toegang tot alle gegevens. DefaultAzureCredential biedt verbeterde beveiligingsfuncties en voordelen en is de aanbevolen benadering voor het beheren van autorisatie voor Azure-services.
/**
* Best practice - use managed identity to avoid keys & connection strings
* managed identity is implemented with @azure/identity's DefaultAzureCredential
*
* The identity that the managed identity chain selects must have the
* correct roles applied in order to work correctly.
*
* For local development: add your personal identity on your resource group
* az role assignment create --assignee "<your-username>" \
* --role "Blob Data Contributor" \
* --resource-group "<your-resource-group-name>"
**/
//const logger = require('@azure/logger');
//logger.setLogLevel('info');
//<Snippet_Dependencies>
import {
BlobSASPermissions,
BlobSASSignatureValues,
BlobServiceClient,
BlockBlobClient,
BlockBlobUploadHeaders,
BlockBlobUploadResponse,
generateBlobSASQueryParameters,
SASProtocol,
SASQueryParameters,
ServiceGetUserDelegationKeyResponse
} from '@azure/storage-blob';
// used for local environment variables
import * as dotenv from 'dotenv';
dotenv.config();
// Get BlobServiceClient
import { getBlobServiceClientFromDefaultAzureCredential } from './auth-get-client';
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME as string;
const blobServiceClient: BlobServiceClient =
getBlobServiceClientFromDefaultAzureCredential();
//</Snippet_Dependencies>
//<Snippet_CreateBlobSas>
// Server creates User Delegation SAS Token for blob
async function createBlobSas(
blobServiceClient: BlobServiceClient,
blobName: string
): Promise<string> {
const containerName = 'my-container';
// Best practice: create time limits
const TEN_MINUTES = 10 * 60 * 1000;
const NOW = new Date();
// Best practice: set start time a little before current time to
// make sure any clock issues are avoided
const TEN_MINUTES_BEFORE_NOW = new Date(NOW.valueOf() - TEN_MINUTES);
const TEN_MINUTES_AFTER_NOW = new Date(NOW.valueOf() + TEN_MINUTES);
// Best practice: delegation key is time-limited
// When using a user delegation key, container must already exist
const userDelegationKey: ServiceGetUserDelegationKeyResponse =
await blobServiceClient.getUserDelegationKey(
TEN_MINUTES_BEFORE_NOW,
TEN_MINUTES_AFTER_NOW
);
if (userDelegationKey.errorCode) throw Error(userDelegationKey.errorCode);
// Need only create/write permission to upload file
const blobPermissionsForAnonymousUser = 'cw';
// Best practice: SAS options are time-limited
const sasOptions: BlobSASSignatureValues = {
blobName,
containerName,
permissions: BlobSASPermissions.parse(blobPermissionsForAnonymousUser),
protocol: SASProtocol.HttpsAndHttp,
startsOn: TEN_MINUTES_BEFORE_NOW,
expiresOn: TEN_MINUTES_AFTER_NOW
};
const sasQueryParameters: SASQueryParameters = generateBlobSASQueryParameters(
sasOptions,
userDelegationKey,
accountName
);
const sasToken: string = sasQueryParameters.toString();
return sasToken;
}
//</Snippet_CreateBlobSas>
//<Snippet_UploadToBlob>
// Client or another process uses SAS token to upload content to blob
async function uploadStringToBlob(
blobName: string,
sasToken,
textAsString: string
): Promise<BlockBlobUploadHeaders> {
// Get environment variables
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME as string;
const containerName = 'my-container';
// Create Url SAS token as query string with typical `?` delimiter
const sasUrl = `https://${accountName}.blob.core.windows.net/${containerName}/${blobName}?${sasToken}`;
console.log(`\nBlobUrl = ${sasUrl}\n`);
// Create blob client from SAS token url
const blockBlobClient = new BlockBlobClient(sasUrl);
// Upload string
const blockBlobUploadResponse: BlockBlobUploadHeaders =
await blockBlobClient.upload(textAsString, textAsString.length, undefined);
if (blockBlobUploadResponse.errorCode)
throw Error(blockBlobUploadResponse.errorCode);
return blockBlobUploadResponse;
}
//</Snippet_UploadToBlob>
//<Snippet_Main>
async function main(blobServiceClient: BlobServiceClient) {
// Create random blob name for text file
const blobName = `${(0 | (Math.random() * 9e6)).toString(36)}.txt`;
// Server creates SAS Token
const userDelegationSasForBlob: string = await createBlobSas(
blobServiceClient,
blobName
);
// Server hands off SAS Token & blobName to client to
// Upload content
const result: BlockBlobUploadHeaders = await uploadStringToBlob(
blobName,
userDelegationSasForBlob,
'Hello Blob World'
);
if (result.errorCode) throw Error(result.errorCode);
console.log(`\n${blobName} uploaded successfully ${result.lastModified}\n`);
}
main(blobServiceClient)
.then(() => {
console.log(`success`);
})
.catch((err: unknown) => {
if (err instanceof Error) {
console.log(err.message);
}
});
//</Snippet_Main>
Notitie
Voor scenario's waarin SHARED Access Signatures (SAS) worden gebruikt, raadt Microsoft aan een SAS voor gebruikersdelegering te gebruiken. Een SAS voor gebruikersdelegering wordt beveiligd met Microsoft Entra-referenties in plaats van de accountsleutel. Zie Een SAS voor gebruikersdelegatie maken met JavaScript voor meer informatie.
Het dotenv pakket wordt gebruikt om de naam van uw opslagaccount uit een .env bestand te lezen. Dit bestand mag niet worden ingecheckt bij broncodebeheer.
Binnenkort beschikbaar: In de loop van 2024 zullen we GitHub-problemen geleidelijk uitfaseren als het feedbackmechanisme voor inhoud en deze vervangen door een nieuw feedbacksysteem. Zie voor meer informatie: https://aka.ms/ContentUserFeedback.