gcfabri
gcfabri

Reputation: 574

How to make Azure File Storage URLs public using Node.js?

When I try to access the generated URL, some header values error appears. Based on other related question, was suggested to append the shared access signature to the URL. Now when I try to access the URL, some authentication error appears. What I am doing wrong?

This is what I've tried:

export default (fileData) => {
  let fileToUpload = `boleto.pdf`;
  let shareName = `boleto-` + uuid.v1();
  let directoryName = `boletos`;
  let fileName = fileToUpload;
  let startDate = new Date();
  let expiryDate = new Date(startDate);

  const fileService = storage.createFileService();

  const sasToken = fileService.generateSharedAccessSignature(shareName, directoryName, fileName, {
    AccessPolicy: {
      Permissions: storage.FileUtilities.SharedAccessPermissions.READ,
      Start: startDate,
      Expiry: expiryDate
    }
  });

  const sharedFileService = storage.createFileService(`DefaultEndpointsProtocol=https;AccountName=${process.env.AZURE_STORAGE_ACCOUNT};AccountKey=${process.env.AZURE_STORAGE_KEY};EndpointSuffix=core.windows.net`);

  sharedFileService.createShareIfNotExists(shareName, (err) => {
    if (err) throw new Error(err);
    sharedFileService.createDirectoryIfNotExists(shareName, directoryName, (err) => {
      if (err) throw new Error(err);
      let nextDirectoryName = directoryName + `/` + directoryName + `01`;
      fileService.createDirectoryIfNotExists(shareName, nextDirectoryName, (err) => {
        if (err) throw new Error(err);
        sharedFileService.createFileFromStream(shareName, directoryName, fileName, fileData.stream, fileData.buffer.length, (err, result, response) => {
          if (err) throw new Error(err);
          console.log(`FILE UPLOADED!`);
          const url = sharedFileService.getUrl(shareName, directoryName, fileName);
          console.log(`URL: ${JSON.stringify(url)}?sv=${sasToken}`);
        });
      });
    });
  });
};

Upvotes: 0

Views: 273

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136306

I see two issues with your code:

  1. Your startDate and expiryDate are the same and that too set as current date. What this will do is make your sas token expire as soon as it is created. You should set expiry date to a date/time value in future.
  2. You're including sv parameter in your query string which is not needed as sv is already included in your sas token.

    console.log(URL: ${JSON.stringify(url)}?sv=${sasToken});

Please change this to something like the following:

console.log(`URL: ${url}?${sasToken}`);

This URL should not give you authentication error.

Upvotes: 1

Related Questions