Unable to upload to blob storage, missing Access-Control-Allow-Origin header

情到浓时终转凉″ 提交于 2020-06-28 08:10:22

问题


Using the @azure/storage-blob module in the browser, it's not possible to upload to azure storage directly. It complains about a missing request header. The upload is done from within a ReactJS app running as an Office Add-in.

As required by Microsoft, CORS have been enabled on storage account for blobs.

I tried finding a way to add custom HTTP Headers however, none worked.

Here's the upload code

import { Credential, BlobServiceClient} from "@azure/storage-blob/browser/azure-storage-blob.min.js";

export function uploadToStorage(storageAccountName: string, storageAccountKey: string, file: SelectedFile) {
    return async (dispatch) => {
        try {
            const account = storageAccountName;
            const accountKey = storageAccountKey;
            const sharedKeyCredential = new Credential(account, accountKey);
            const blobServiceClient = new BlobServiceClient(
                `https://${account}.blob.core.windows.net`,
                sharedKeyCredential
            );
            const containerClient = blobServiceClient.getContainerClient("container-name");
            const blobClient = containerClient.getBlobClient(file.name);
            const blockBlobClient = blobClient.getBlockBlobClient();
            const uploadBlobResponse = await blockBlobClient.uploadBrowserData(file.data, {
                maxSingleShotSize: 4 * 1024 * 1024
              }, { "blobHTTPHeaders": { "blobContentType": file.mimeType } });
        }
        catch (error) { 
            console.error(error);
        }
    }
}

The error from Chrome Debugger is as follow:

Access to XMLHttpRequest at 'https://somestorageaccountsomewhere.blob.core.windows.net/blablablacontainer/Somefile-2018.5-en.docx' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.


回答1:


It's not a good idea to upload blobs directly from the browser. Your access key is compromised since it is available to anyone viewing the app. The effects can be quite severe since anyone could for example: delete all your files / upload massive amounts of data causing your Azure bill to skyrocket.

You will need to do the upload in a back-end or use a SAS token generated in a back-end to upload the file.

There is also the option of Azure AD authentication, but requires some setup, and the user needs data access role on the Storage account or container.



来源:https://stackoverflow.com/questions/57912513/unable-to-upload-to-blob-storage-missing-access-control-allow-origin-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!