Skip to content

Commit fda9bf8

Browse files
Merge pull request #245444 from pauljewellmsft/pauljewell-cpp-quickstart
Refresh C++ quickstart for passwordless
2 parents a34e322 + d01606f commit fda9bf8

File tree

1 file changed

+150
-43
lines changed

1 file changed

+150
-43
lines changed

articles/storage/blobs/quickstart-blobs-c-plus-plus.md

Lines changed: 150 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,57 @@
11
---
2-
title: "Quickstart: Azure Blob Storage library v12 - C++"
2+
title: "Quickstart: Azure Blob Storage library - C++"
33
titleSuffix: Azure Storage
4-
description: In this quickstart, you learn how to use the Azure Blob Storage client library version 12 for C++ to create a container and a blob in Blob (object) storage. Next, you learn how to download the blob to your local computer, and how to list all of the blobs in a container.
4+
description: In this quickstart, you learn how to use the Azure Blob Storage client library for C++ to create a container and a blob in Blob (object) storage. Next, you learn how to download the blob to your local computer, and how to list all of the blobs in a container.
55
author: pauljewellmsft
66

77
ms.author: pauljewell
8-
ms.date: 06/21/2021
9-
ms.service: azure-storage
8+
ms.date: 08/30/2023
9+
ms.service: azure-blob-storage
1010
ms.topic: quickstart
1111
ms.devlang: cpp
1212
ms.custom: mode-api
1313
---
1414

15-
# Quickstart: Azure Blob Storage client library v12 for C++
15+
# Quickstart: Azure Blob Storage client library for C++
1616

17-
Get started with the Azure Blob Storage client library v12 for C++. Azure Blob Storage is Microsoft's object storage solution for the cloud. Follow steps to install the package and try out example code for basic tasks. Blob Storage is optimized for storing massive amounts of unstructured data.
17+
Get started with the Azure Blob Storage client library for C++. Azure Blob Storage is Microsoft's object storage solution for the cloud. Follow these steps to install the package and try out example code for basic tasks.
1818

19-
Use the Azure Blob Storage client library v12 for C++ to:
20-
21-
- Create a container
22-
- Upload a blob to Azure Storage
23-
- List all of the blobs in a container
24-
- Download the blob to your local computer
25-
- Delete a container
26-
27-
Resources:
28-
29-
- [API reference documentation](https://azure.github.io/azure-sdk-for-cpp/storage.html)
30-
- [Library source code](https://github.com/Azure/azure-sdk-for-cpp/tree/master/sdk/storage)
31-
- [Samples](../common/storage-samples-c-plus-plus.md?toc=/azure/storage/blobs/toc.json)
19+
| [API reference documentation](https://azure.github.io/azure-sdk-for-cpp/storage.html) | [Library source code](https://github.com/Azure/azure-sdk-for-cpp/tree/master/sdk/storage) | [Samples](../common/storage-samples-c-plus-plus.md?toc=/azure/storage/blobs/toc.json) |
3220

3321
## Prerequisites
3422

35-
- [Azure subscription](https://azure.microsoft.com/free/)
36-
- [Azure storage account](../common/storage-account-create.md)
23+
- Azure subscription - [create one for free](https://azure.microsoft.com/free/)
24+
- Azure storage account - [create a storage account](../common/storage-account-create.md)
3725
- [C++ compiler](https://azure.github.io/azure-sdk/cpp_implementation.html#supported-platforms)
3826
- [CMake](https://cmake.org/)
39-
- [Vcpkg - C and C++ package manager](https://github.com/microsoft/vcpkg/blob/master/README.md)
27+
- [vcpkg - C and C++ package manager](https://vcpkg.io/en/getting-started.html)
4028

4129
## Setting up
4230

43-
This section walks you through preparing a project to work with the Azure Blob Storage client library v12 for C++.
31+
This section walks you through preparing a project to work with the Azure Blob Storage client library for C++. The easiest way to acquire the Azure SDK for C++ is to use the `vcpkg` package manager.
4432

4533
### Install the packages
4634

47-
The `vcpkg install` command will install the Azure Storage Blobs SDK for C++ and necessary dependencies:
35+
Use the `vcpkg install` command to install the Azure Blob Storage library for C++ and necessary dependencies:
36+
37+
```console
38+
vcpkg.exe install azure-storage-blobs-cpp
39+
```
40+
41+
The Azure Identity library is needed for passwordless connections to Azure services:
4842

4943
```console
50-
vcpkg.exe install azure-storage-blobs-cpp:x64-windows
44+
vcpkg.exe install azure-identity-cpp
5145
```
5246

53-
For more information, visit GitHub to acquire and build the [Azure SDK for C++](https://github.com/Azure/azure-sdk-for-cpp/).
47+
For more information on project setup and working with the Azure SDK for C++, see the [Azure SDK for C++ readme](https://github.com/Azure/azure-sdk-for-cpp#azure-sdk-for-c).
5448

5549
### Create the project
5650

57-
In Visual Studio, create a new C++ console application for Windows called *BlobQuickstartV12*.
51+
In Visual Studio, create a new C++ console application for Windows called *BlobQuickstart*.
5852

5953
:::image type="content" source="./media/quickstart-blobs-c-plus-plus/vs-create-project.jpg" alt-text="Visual Studio dialog for configuring a new C++ Windows console app":::
6054

61-
[!INCLUDE [storage-quickstart-credentials-include](../../../includes/storage-quickstart-credentials-include.md)]
62-
6355
## Object model
6456

6557
Azure Blob Storage is optimized for storing massive amounts of unstructured data. Unstructured data is data that doesn't adhere to a particular data model or definition, such as text or binary data. Blob Storage offers three types of resources:
@@ -84,7 +76,7 @@ Use these C++ classes to interact with these resources:
8476
These example code snippets show you how to do the following tasks with the Azure Blob Storage client library for C++:
8577

8678
- [Add include files](#add-include-files)
87-
- [Get the connection string](#get-the-connection-string)
79+
- [Authenticate to Azure and authorize access to blob data](#authenticate-to-azure-and-authorize-access-to-blob-data)
8880
- [Create a container](#create-a-container)
8981
- [Upload blobs to a container](#upload-blobs-to-a-container)
9082
- [List the blobs in a container](#list-the-blobs-in-a-container)
@@ -95,37 +87,152 @@ These example code snippets show you how to do the following tasks with the Azur
9587

9688
From the project directory:
9789

98-
1. Open the *BlobQuickstartV12.sln* solution file in Visual Studio
99-
1. Inside Visual Studio, open the *BlobQuickstartV12.cpp* source file
90+
1. Open the *BlobQuickstart.sln* solution file in Visual Studio
91+
1. Inside Visual Studio, open the *BlobQuickstart.cpp* source file
10092
1. Remove any code inside `main` that was autogenerated
101-
1. Add `#include` statements
93+
1. Add `#include` and `using namespace` statements
94+
95+
```cpp
96+
#include <iostream>
97+
#include <azure/core.hpp>
98+
#include <azure/identity/default_azure_credential.hpp>
99+
#include <azure/storage/blobs.hpp>
100+
101+
using namespace Azure::Identity;
102+
using namespace Azure::Storage::Blobs;
103+
```
104+
105+
### Authenticate to Azure and authorize access to blob data
106+
107+
Application requests to Azure Blob Storage must be authorized. Using the `DefaultAzureCredential` class provided by the Azure Identity client library is the recommended approach for implementing passwordless connections to Azure services in your code, including Blob Storage.
108+
109+
You can also authorize requests to Azure Blob Storage by using the account access key. However, this approach should be used with caution. Developers must be diligent to never expose the access key in an unsecure location. Anyone who has the access key is able to authorize requests against the storage account, and effectively has access to all the data. `DefaultAzureCredential` offers improved management and security benefits over the account key to allow passwordless authentication. Both options are demonstrated in the following example.
110+
111+
### [Passwordless (Recommended)](#tab/managed-identity)
112+
113+
The Azure Identity library provides Azure Active Directory (Azure AD) token authentication support across the Azure SDK. It provides a set of `TokenCredential` implementations which can be used to construct Azure SDK clients which support Azure AD token authentication. `DefaultAzureCredential` supports multiple authentication methods and determines which method should be used at runtime.
114+
115+
#### Assign roles to your Azure AD user account
116+
117+
[!INCLUDE [assign-roles](../../../includes/assign-roles.md)]
118+
119+
#### Sign in and connect your app code to Azure using DefaultAzureCredential
120+
121+
You can authorize access to data in your storage account using the following steps:
122+
123+
1. Make sure you're authenticated with the same Azure AD account you assigned the role to on your storage account. You can authenticate via [Azure CLI](/cli/azure/install-azure-cli). Sign in to Azure through the Azure CLI using the following command:
124+
125+
```azurecli
126+
az login
127+
```
128+
129+
2. To use `DefaultAzureCredential`, make sure that the **azure-identity-cpp** package is [installed](#install-the-packages) and the following `#include` is added:
130+
131+
```cpp
132+
#include <azure/identity/default_azure_credential.hpp>
133+
```
134+
135+
3. Add this code to the end of `main()`. When the code runs on your local workstation, `DefaultAzureCredential` uses the developer credentials for Azure CLI to authenticate to Azure.
102136
103-
:::code language="cpp" source="~/azure-storage-snippets/blobs/quickstarts/C++/V12/BlobQuickstartV12/BlobQuickstartV12/BlobQuickstartV12.cpp" ID="Snippet_Includes":::
137+
```cpp
138+
// Initialize an instance of DefaultAzureCredential
139+
auto defaultAzureCredential = std::make_shared<DefaultAzureCredential>();
104140
105-
### Get the connection string
141+
auto accountURL = "https://<storage-account-name>.blob.core.windows.net";
142+
BlobServiceClient blobServiceClient(accountURL, defaultAzureCredential);
143+
```
106144
107-
The code below retrieves the connection string for your storage account from the environment variable created in [Configure your storage connection string](#configure-your-storage-connection-string).
145+
4. Make sure to update the storage account name in the URI of your `BlobServiceClient` object. The storage account name can be found on the overview page of the Azure portal.
108146
109-
Add this code inside `main()`:
147+
:::image type="content" source="./media/storage-quickstart-blobs-dotnet/storage-account-name.png" alt-text="A screenshot showing how to find the storage account name.":::
110148
111-
:::code language="cpp" source="~/azure-storage-snippets/blobs/quickstarts/C++/V12/BlobQuickstartV12/BlobQuickstartV12/BlobQuickstartV12.cpp" ID="Snippet_ConnectionString":::
149+
> [!NOTE]
150+
> When using the C++ SDK in a production environment, it's recommended that you only enable credentials that you know your application will use. Instead of using `DefaultAzureCredential`, you should authorize using a specific credential type, or by using `ChainedTokenCredential` with the supported credentials.
151+
152+
### [Connection String](#tab/connection-string)
153+
154+
A connection string includes the storage account access key and uses it to authorize requests. Always be careful to never expose the keys in an unsecure location.
155+
156+
> [!NOTE]
157+
> To authorize data access with the storage account access key, you'll need permissions for the following Azure RBAC action: [Microsoft.Storage/storageAccounts/listkeys/action](../../role-based-access-control/resource-provider-operations.md#microsoftstorage). The least privileged built-in role with permissions for this action is [Reader and Data Access](../../role-based-access-control/built-in-roles.md#reader-and-data-access), but any role which includes this action will work.
158+
159+
[!INCLUDE [retrieve credentials](../../../includes/retrieve-credentials.md)]
160+
161+
#### Configure your storage connection string
162+
163+
After you copy the connection string, write it to a new environment variable on the local machine running the application. To set the environment variable, open a console window, and follow the instructions for your operating system. Replace `<yourconnectionstring>` with your actual connection string.
164+
165+
**Windows**:
166+
167+
```cmd
168+
setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"
169+
```
170+
171+
After you add the environment variable in Windows, you must start a new instance of the command window.
172+
173+
**Linux**:
174+
175+
```bash
176+
export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"
177+
```
178+
179+
The following code example retrieves the connection string for the storage account from the environment variable created earlier, and uses the connection string to construct a service client object.
180+
181+
Add this code to the end of `main()`:
182+
183+
```cpp
184+
// Retrieve the connection string for use with the application. The storage
185+
// connection string is stored in an environment variable on the machine
186+
// running the application called AZURE_STORAGE_CONNECTION_STRING.
187+
// Note that _MSC_VER is set when using MSVC compiler.
188+
static const char* AZURE_STORAGE_CONNECTION_STRING = "AZURE_STORAGE_CONNECTION_STRING";
189+
190+
#if !defined(_MSC_VER)
191+
const char* connectionString = std::getenv(AZURE_STORAGE_CONNECTION_STRING);
192+
#else
193+
// Use getenv_s for MSVC
194+
size_t requiredSize;
195+
getenv_s(&requiredSize, NULL, NULL, AZURE_STORAGE_CONNECTION_STRING);
196+
if (requiredSize == 0) {
197+
throw std::runtime_error("missing connection string from env.");
198+
}
199+
std::vector<char> value(requiredSize);
200+
getenv_s(&requiredSize, value.data(), value.size(), AZURE_STORAGE_CONNECTION_STRING);
201+
std::string connectionStringStr = std::string(value.begin(), value.end());
202+
const char* connectionString = connectionStringStr.c_str();
203+
#endif
204+
205+
auto blobServiceClient = BlobServiceClient::CreateFromConnectionString(connectionString);
206+
```
207+
208+
> [!IMPORTANT]
209+
> The account access key should be used with caution. If your account access key is lost or accidentally placed in an insecure location, your service may become vulnerable. Anyone who has the access key is able to authorize requests against the storage account, and effectively has access to all the data. `DefaultAzureCredential` provides enhanced security features and benefits and is the recommended approach for managing authorization to Azure services.
210+
211+
---
112212

113213
### Create a container
114214

115-
Create an instance of the [BlobContainerClient](https://azuresdkdocs.blob.core.windows.net/$web/cpp/azure-storage-blobs/12.0.0/class_azure_1_1_storage_1_1_blobs_1_1_blob_container_client.html) class by calling the [CreateFromConnectionString](https://azuresdkdocs.blob.core.windows.net/$web/cpp/azure-storage-blobs/12.0.0/class_azure_1_1_storage_1_1_blobs_1_1_blob_container_client.html#a5d253aacb6e20578b7f5f233547be3e2) function. Then call [CreateIfNotExists](https://azuresdkdocs.blob.core.windows.net/$web/cpp/azure-storage-blobs/12.0.0/class_azure_1_1_storage_1_1_blobs_1_1_blob_container_client.html#ab3ef187d2e30e1a19ebadf45d0fdf9c4) to create the actual container in your storage account.
215+
Decide on a name for the new container. Then create an instance of `BlobContainerClient` and create the container.
116216

117217
> [!IMPORTANT]
118218
> Container names must be lowercase. For more information about naming containers and blobs, see [Naming and Referencing Containers, Blobs, and Metadata](/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata).
119219

120220
Add this code to the end of `main()`:
121221

122-
:::code language="cpp" source="~/azure-storage-snippets/blobs/quickstarts/C++/V12/BlobQuickstartV12/BlobQuickstartV12/BlobQuickstartV12.cpp" ID="Snippet_CreateContainer":::
222+
```cpp
223+
std::string containerName = "myblobcontainer";
224+
auto containerClient = blobServiceClient.GetBlobContainerClient("myblobcontainer");
225+
226+
// Create the container if it does not exist
227+
std::cout << "Creating container: " << containerName << std::endl;
228+
containerClient.CreateIfNotExists();
229+
```
123230

124231
### Upload blobs to a container
125232

126233
The following code snippet:
127234

128-
1. Declares a string containing "Hello Azure!".
235+
1. Declares a string containing "Hello Azure!"
129236
1. Gets a reference to a [BlockBlobClient](https://azuresdkdocs.blob.core.windows.net/$web/cpp/azure-storage-blobs/1.0.0-beta.2/class_azure_1_1_storage_1_1_blobs_1_1_block_blob_client.html) object by calling [GetBlockBlobClient](https://azuresdkdocs.blob.core.windows.net/$web/cpp/azure-storage-blobs/1.0.0-beta.2/class_azure_1_1_storage_1_1_blobs_1_1_blob_container_client.html#acd8c68e3f37268fde0010dd478ff048f) on the container from the [Create a container](#create-a-container) section.
130237
1. Uploads the string to the blob by calling the [​Upload​From](https://azuresdkdocs.blob.core.windows.net/$web/cpp/azure-storage-blobs/1.0.0-beta.2/class_azure_1_1_storage_1_1_blobs_1_1_block_blob_client.html#af93af7e37f8806e39481596ef253f93d) function. This function creates the blob if it doesn't already exist, or updates it if it does.
131238

@@ -170,7 +277,7 @@ This app creates a container and uploads a text file to Azure Blob Storage. The
170277
The output of the app is similar to the following example:
171278

172279
```output
173-
Azure Blob Storage v12 - C++ quickstart sample
280+
Azure Blob Storage - C++ quickstart sample
174281
Creating container: myblobcontainer
175282
Uploading blob: blob.txt
176283
Listing blobs...
@@ -187,4 +294,4 @@ In this quickstart, you learned how to upload, download, and list blobs using C+
187294
To see a C++ Blob Storage sample, continue to:
188295

189296
> [!div class="nextstepaction"]
190-
> [Azure Blob Storage SDK v12 for C++ sample](https://github.com/Azure/azure-sdk-for-cpp/tree/main/sdk/storage/azure-storage-blobs/samples)
297+
> [Azure Blob Storage client library for C++ samples](https://github.com/Azure/azure-sdk-for-cpp/tree/main/sdk/storage/azure-storage-blobs/samples)

0 commit comments

Comments
 (0)