2

I am now trying to use Service Principal to access azure blob storage in nodes, instead of using connection string.

What I did (and succeeded) is using connection string as follows:

// connect via connection string
const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING;
const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);

Now I want to use Service Principal instead of connection string, but I can't seem to make it work. I can see some examples using some token credentials, e.g.

const blobServiceClient = new BlobServiceClient(
    `https://${account}.blob.core.windows.net`,
    defaultAzureCredential
);

Is it possible to use service principal credentials this way, or are there other ways to do this?

markalex
  • 8,623
  • 2
  • 7
  • 32
Saligia
  • 147
  • 1
  • 9

1 Answers1

1

Try this :

const { BlobServiceClient } = require("@azure/storage-blob");
const { ClientSecretCredential } = require("@azure/identity");

const account = '<your accounr name>'
//Using  Service Principal
const appID = ""
const appSec = ""
const tenantID = ""

const clientCred = new ClientSecretCredential(tenantID,appID,appSec)

const blobServiceClient = new BlobServiceClient(
    `https://${account}.blob.core.windows.net`,
    clientCred
);

//try to list all containers in stroage account to check if success
blobServiceClient.listContainers().byPage().next().then(result =>{
    result.value.containerItems.forEach(element => {
       console.log(element.name);
   });

})

Result:

enter image description here

Note:

Before you run this demo, pls make sure that you have granted the required permissions to your Service Principal, details see this official doc.

Stanley Gong
  • 11,522
  • 1
  • 8
  • 16
  • Thanks! seems like I can list out the containers but cannot access the blobs within, probably something wrong with the sp permissions, I was given the role `Storage Account Contributor`, do you know whether that is relevant? Anyway you still solved my problem of authenticating using service principal credentials, so thanks again! – Saligia Mar 18 '21 at 05:04
  • Welcome If you want to access blob content , try to grant Storage Blob Data Contributor Role – Stanley Gong Mar 18 '21 at 05:24