Search code examples
restazureazure-storageazure-blob-storagecpprest-sdk

Access Azure storage service using cpprest SDK


I am trying to list blobs in my Azure storage account using cpprest sdk and this is my code:

pplx::task<void> HTTPRequestCustomHeadersAsync()
{
    http_client client(L"https://<account-name>.blob.core.windows.net/?comp=list");

    // Manually build up an HTTP request with header and request URI.
    http_request request(methods::GET);
    request.headers().add(L"Authorization", L"Sharedkey <account-name>:<account-key>");
    request.headers().add(L"x-ms-date", L"Thu, 08 Feb 2018 20:31:55 GMT ");
    request.headers().add(L"x-ms-version", L"2017-07-29");

    return client.request(request).then([](http_response response)
    {
        // Print the status code.
        std::wostringstream ss;
        ss << L"Server returned returned status code " << response.status_code() << L"." << std::endl;
        std::wcout << ss.str();
    });

    /* Sample output:
    Server returned returned status code 200.
    */
}

I keep getting the returned status code as 403. Can someone please let me know if I am doing it right?


Solution

  • Please note that you're not using the cpprest-sdk in a correct way, since what you did in the code above was trying to invoke Azure Storage REST API directly (and incorrectly) without going through cpprest-sdk at all.

    Actually, account key in the HTTP header of Azure Storage REST API contract is not a plain text. Instead, it's calculated by complex steps mentioned in Authentication for the Azure Storage Services for a bunch of security considerations. Fortunately, all those logic have been wrapped by cpprest-sdk, you don't need to understand how it works internally:

    // Define the connection-string with your values.
    const utility::string_t storage_connection_string(U("DefaultEndpointsProtocol=https;AccountName=your_storage_account;AccountKey=your_storage_account_key"));
    
    // Create the blob client.
    azure::storage::cloud_blob_client blob_client = storage_account.create_cloud_blob_client();  
    

    I'd suggest you to read How to use Blob Storage from C++ at first before using cpprest-sdk.