简体   繁体   English

NodeJS Azure存储返回403

[英]NodeJS Azure Storage returns 403

I have a NodeJS API which access Azure Storage. 我有一个可访问Azure存储的NodeJS API。 API is hosted on Windows Server 2016, IIS 10.0 with IISNode. API托管在Windows Server 2016,带有IISNode的IIS 10.0上。 I am using HapiJS Framework. 我正在使用HapiJS Framework。

The API worked fine with Azure Storage Emulator, when we moved to staged environment and changed the connection string to azure storage, Azure storage returned 403,forbidden. 当我们移至暂存环境并将连接字符串更改为Azure存储时,该API与Azure Storage Emulator可以很好地工作,Azure存储返回403(禁止)。

Below is logged information: 以下是记录的信息:

[2018-03-05T16:06:36.257Z]debug : FINAL REQUEST OPTIONS:
{ uri: 'https://some-container.blob.core.windows.net:443/images?restype=container',
method: 'HEAD',
headers: 
   { 'x-ms-client-request-id': '2e2ea0a0-208f-11e8-9345-559bff0df7cf',
 'user-agent': 'Azure-Storage/2.7.0 (NODE-VERSION v9.5.0; Windows_NT 10.0.14393)',
 'x-ms-version': '2017-04-17',
 'x-ms-date': 'Mon, 05 Mar 2018 16:06:36 GMT',
 accept: 'application/atom+xml,application/xml',
 'Accept-Charset': 'UTF-8',
 'content-type': '',
 'content-length': 0,
 authorization: 'SharedKey container:someKeyHere' },
mode: 'disable-fetch',
encoding: undefined,
timeout: 120000,
forever: true }

[2018-03-05T16:06:37.188Z]debug : RESPONSE:
{ error: 
   { StorageError: Forbidden
at Function.StorageServiceClient._normalizeError (C:\Load2.0\Staged\Backend\node_modules\azure-storage\lib\common\services\storageserviceclient.js:1191:23)
at BlobService.StorageServiceClient._processResponse (C:\Load2.0\Staged\Backend\node_modules\azure-storage\lib\common\services\storageserviceclient.js:738:50)
at Request.processResponseCallback [as _callback] (C:\Load2.0\Staged\Backend\node_modules\azure-storage\lib\common\services\storageserviceclient.js:311:37)
at Request.self.callback (C:\Load2.0\Staged\Backend\node_modules\azure-storage\node_modules\request\request.js:188:22)
at Request.emit (events.js:160:13)
at Request.<anonymous> (C:\Load2.0\Staged\Backend\node_modules\azure-storage\node_modules\request\request.js:1171:10)
at Request.emit (events.js:160:13)
at IncomingMessage.<anonymous> (C:\Load2.0\Staged\Backend\node_modules\azure-storage\node_modules\request\request.js:1091:12)
at Object.onceWrapper (events.js:255:19)
at IncomingMessage.emit (events.js:165:20)
at endReadableNT (_stream_readable.js:1101:12)
at process._tickCallback (internal/process/next_tick.js:152:19)
 name: 'StorageError',
 message: 'Forbidden',
 code: 'Forbidden',
 statusCode: 403,
 requestId: '2354daf1-001e-007c-25ac-b48832000000' },
  response: 
   { isSuccessful: false,
 statusCode: 403,
 body: '',
 headers: 
  { 'transfer-encoding': 'chunked',
    server: 'Microsoft-HTTPAPI/2.0',
    'x-ms-request-id': '2354daf1-001e-007c-25ac-b48832000000',
    date: 'Mon, 05 Mar 2018 18:06:36 GMT' },
 md5: undefined } }

I do not know why I get 403, I have copied connection string from Azure Portal and double checked multiple times. 我不知道为什么得到403,我从Azure门户复制了连接字符串,并多次检查。

Below is the source code I am using: 以下是我正在使用的源代码:

const azureStorage = require("azure-storage");
const shortId = require("shortid");

class AzureBlobService {
    constructor(connectionString){
        this.connectionString = connectionString;
        this.blobService = azureStorage.createBlobService(this.connectionString);
    }

    /**
     * Upload a file
     * @param {*} fileBuffer 
     * @param {*} filename
     * @param {*} container
     * @param {*} callback
     */
    uploadFile(fileBuffer, filename, container, callback) {
        let fileExtension = filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2);
        this.blobService.createContainerIfNotExists(containerToUse, err => {
            if (err) {
                callback(err, { message: "Failed to create blob container" });
            } else {
                let blobName = shortId.generate() + "." + fileExtension;
                this.blobService.createBlockBlobFromStream(containerToUse, blobName, 
                this._bufferToStream(fileBuffer), fileBuffer.length, err => {
                if (err) {
                    callback(err, { message: "Failed to upload blob" });
                } else {
                    let sasToken = this.blobService.generateSharedAccessSignature(containerToUse, blobName, 
                        { AccessPolicy: { Expiry: azureStorage.date.minutesFromNow(10) } });
                        let sasUrl = this.blobService.getUrl(containerToUse, blobName, sasToken, true);

                        // TODO: return URL
                        callback(null, { url: sasUrl, blobName: blobName });
                    }
                });
            }
        });
    }

    /**
     * Convert a buffer to stream
     * @param {*} buffer 
     */
    _bufferToStream(buffer) {
        let stream = new Duplex();
        stream.push(buffer);
        stream.push(null);
        return stream;
    }
}

For azure-storage-node, you can create blobService object by account key or a SAS token. 对于azure-storage-node,可以通过帐户密钥或SAS令牌创建blobService对象。 For example, when using storage account key generated from Azure Portal: 例如,当使用从Azure门户生成的存储帐户密钥时:

var blobService = azureStorage.createBlobService(accountName, accountKey).withFilter(new azureStorage.ExponentialRetryPolicyFilter());

blobService.logger = new azureStorage.Logger();
blobService.createContainerIfNotExists('1mycontainer', function (err, res) {
  if (!err) {
    blobService.createBlockBlobFromLocalFile('1mycontainer', 'taskblob', 'task1.txt', function (error, result, response) {
      if (!error) {
          console.log("uploaded");
      } else {
          console.log(error);
      }
    }); 
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM