user3548808
user3548808

Reputation: 103

How to generate SAS token in azure JS SDK, from app client, without using account key

How to pre-sign Url in azure using javascript SDK with App registrations - Application (client) ID, client secret (value), Tenant_id and also account name, container name, blob name. I am not able to generate Container Level SAS token for giving temporary access to my files.

    const account = "accountName";
    const containerName = "containerName";
    const blobName = "blob";

    const credential = new ClientSecretCredential(
        "AZURE_TENANT_ID",
        "AZURE_CLIENT_ID",
        "AZURE_CLIENT_SECRET"
    );

    const blobServiceClient = new BlobServiceClient(
        `https://${account}.blob.core.windows.net`,
        credential
        );
    
    const containerClient = blobServiceClient.getContainerClient(containerName);
    let blobs = containerClient.listBlobsFlat({includeMetadata: true}); // works ok 


    await credential.getToken(); // how to generate sas token for my container to sign url ? 

I do not want to use the account key, and it seems generateBlobSASQueryParameters function works with account key.

Upvotes: 1

Views: 1062

Answers (2)

Jeremy Meng
Jeremy Meng

Reputation: 469

A user delegation SAS offers superior security to a SAS that is signed with the storage account key. Microsoft recommends using a user delegation SAS when possible

https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-user-delegation-sas-create-dotnet

The link has a .NET sample, but you could translate to javascript.

There are also some test cases here demonstrating the usage: get a user delegation key from BlobServiceClient, then pass the user delegation key to generateBlobSASQueryParameters()

https://github.com/Azure/azure-sdk-for-js/blob/d2730549e078571df008e929f19c07aaf8f9efd9/sdk/storage/storage-blob/test/node/sas.spec.ts#L992-L1004

Upvotes: 1

user3548808
user3548808

Reputation: 103

I have succeeded with the following steps.

Have to add Storage Blob Delegator and Storage Blob Data Reader roles to my application client from storage container IAM, and add the following code to upper one.

const userDelegationKey = await blobServiceClient.getUserDelegationKey(new Date(), new Date(new Date().valueOf() + 86400));
const containerSAS = generateBlobSASQueryParameters({
    containerName,
    permissions: ContainerSASPermissions.parse("r"),
    startsOn: new Date(),
    expiresOn: new Date(new Date().valueOf() + 86400),
    version: "2018-11-09"
 },
 userDelegationKey,
 account
).toString();
console.log(`${containerClient.getBlockBlobClient(blobName).url}?${containerSAS}`);

Upvotes: 2

Related Questions