Skip to content

Commit 6b55427

Browse files
authored
Merge pull request #222943 from diberry/diberry/0104-event-hub
Event hubs JS quickstart passwordless
2 parents 79ff91f + 2b96e19 commit 6b55427

File tree

4 files changed

+365
-34
lines changed

4 files changed

+365
-34
lines changed

articles/event-hubs/event-hubs-node-get-started-send.md

Lines changed: 204 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
---
2-
title: Send or receive events from Azure Event Hubs using JavaScript (latest)
3-
description: This article provides a walkthrough for creating a JavaScript application that sends/receives events to/from Azure Event Hubs using the latest azure/event-hubs package.
2+
title: Send or receive events from Azure Event Hubs using JavaScript
3+
description: This article provides a walkthrough for creating a JavaScript application that sends/receives events to/from Azure Event Hubs.
44
ms.topic: quickstart
5-
ms.date: 02/22/2022
5+
ms.date: 01/04/2023
66
ms.devlang: javascript
7-
ms.custom: devx-track-js, mode-api
7+
ms.custom: devx-track-js, mode-api, passwordless-js
88
---
99

10-
# Send events to or receive events from event hubs by using JavaScript (azure/event-hubs)
11-
This quickstart shows how to send events to and receive events from an event hub using the **azure/event-hubs** JavaScript package.
10+
# Send events to or receive events from event hubs by using JavaScript
11+
This quickstart shows how to send events to and receive events from an event hub using the **@azure/event-hubs** npm package.
1212

1313

1414
## Prerequisites
@@ -17,35 +17,36 @@ If you are new to Azure Event Hubs, see [Event Hubs overview](event-hubs-about.m
1717
To complete this quickstart, you need the following prerequisites:
1818

1919
- **Microsoft Azure subscription**. To use Azure services, including Azure Event Hubs, you need a subscription. If you don't have an existing Azure account, you can sign up for a [free trial](https://azure.microsoft.com/free/) or use your MSDN subscriber benefits when you [create an account](https://azure.microsoft.com).
20-
- Node.js version 8.x or later. Download the latest [long-term support (LTS) version](https://nodejs.org).
20+
- Node.js LTS. Download the latest [long-term support (LTS) version](https://nodejs.org).
2121
- Visual Studio Code (recommended) or any other integrated development environment (IDE).
22-
- An active Event Hubs namespace and event hub. To create them, do the following steps:
22+
- **Create an Event Hubs namespace and an event hub**. The first step is to use the [Azure portal](https://portal.azure.com) to create a namespace of type Event Hubs, and obtain the management credentials your application needs to communicate with the event hub. To create a namespace and an event hub, follow the procedure in [this article](event-hubs-create.md).
2323

24-
1. In the [Azure portal](https://portal.azure.com), create a namespace of type *Event Hubs*, and then obtain the management credentials that your application needs to communicate with the event hub.
25-
1. To create the namespace and event hub, follow the instructions at [Quickstart: Create an event hub by using the Azure portal](event-hubs-create.md).
26-
1. Continue by following the instructions in this quickstart.
27-
1. To get the connection string for your Event Hub namespace, follow the instructions in [Get connection string](event-hubs-get-connection-string.md#azure-portal). Record the connection string to use later in this quickstart.
28-
- **Create an Event Hubs namespace and an event hub**. The first step is to use the [Azure portal](https://portal.azure.com) to create a namespace of type Event Hubs, and obtain the management credentials your application needs to communicate with the event hub. To create a namespace and an event hub, follow the procedure in [this article](event-hubs-create.md). Then, get the **connection string for the Event Hubs namespace** by following instructions from the article: [Get connection string](event-hubs-get-connection-string.md#azure-portal). You use the connection string later in this quickstart.
29-
30-
### Install the npm package
24+
### Install the npm package(s) to send events
3125
To install the [Node Package Manager (npm) package for Event Hubs](https://www.npmjs.com/package/@azure/event-hubs), open a command prompt that has *npm* in its path, change the directory
32-
to the folder where you want to keep your samples, and then run this command:
26+
to the folder where you want to keep your samples.
27+
28+
### [Passwordless (Recommended)](#tab/passwordless)
29+
30+
Run these commands:
3331

3432
```shell
3533
npm install @azure/event-hubs
34+
npm install @azure/identity
3635
```
3736

38-
For the receiving side, you need to install two more packages. In this quickstart, you use Azure Blob storage to persist checkpoints so that the program doesn't read the events that it has already read. It performs metadata checkpoints on received messages at regular intervals in a blob. This approach makes it easy to continue receiving messages later from where you left off.
37+
### [Connection String](#tab/connection-string)
3938

40-
Run the following commands:
39+
Run this command:
4140

4241
```shell
43-
npm install @azure/storage-blob
42+
npm install @azure/event-hubs
4443
```
4544

46-
```shell
47-
npm install @azure/eventhubs-checkpointstore-blob
48-
```
45+
---
46+
47+
### Authenticate the app to Azure
48+
49+
[!INCLUDE [event-hub-passwordless-template-tabbed](../../includes/passwordless/event-hub/event-hub-passwordless-template-tabbed-basic.md)]
4950

5051
## Send events
5152

@@ -54,6 +55,55 @@ In this section, you create a JavaScript application that sends events to an eve
5455
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com).
5556
1. Create a file called *send.js*, and paste the following code into it:
5657

58+
## [Passwordless (Recommended)](#tab/passwordless)
59+
60+
In the code, use real values to replace the following placeholders:
61+
* `EVENT HUBS RESOURCE NAME`
62+
* `EVENT HUB NAME`
63+
64+
```javascript
65+
const { EventHubProducerClient } = require("@azure/event-hubs");
66+
const { DefaultAzureCredential } = require("@azure/identity");
67+
68+
// Event hubs
69+
const eventHubsResourceName = "EVENT HUBS RESOURCE NAME";
70+
const fullyQualifiedNamespace = `${eventHubsResourceName}.servicebus.windows.net`;
71+
const eventHubName = "EVENT HUB NAME";
72+
73+
// Azure Identity - passwordless authentication
74+
const credential = new DefaultAzureCredential();
75+
76+
async function main() {
77+
78+
// Create a producer client to send messages to the event hub.
79+
const producer = new EventHubProducerClient(fullyQualifiedNamespace, eventHubName, credential);
80+
81+
// Prepare a batch of three events.
82+
const batch = await producer.createBatch();
83+
batch.tryAdd({ body: "passwordless First event" });
84+
batch.tryAdd({ body: "passwordless Second event" });
85+
batch.tryAdd({ body: "passwordless Third event" });
86+
87+
// Send the batch to the event hub.
88+
await producer.sendBatch(batch);
89+
90+
// Close the producer client.
91+
await producer.close();
92+
93+
console.log("A batch of three events have been sent to the event hub");
94+
}
95+
96+
main().catch((err) => {
97+
console.log("Error occurred: ", err);
98+
});
99+
```
100+
101+
## [Connection String](#tab/connection-string)
102+
103+
In the code, use real values to replace the following placeholders:
104+
* `EVENT HUB NAME`
105+
* `EVENT HUBS NAMESPACE CONNECTION STRING`
106+
57107
```javascript
58108
const { EventHubProducerClient } = require("@azure/event-hubs");
59109
@@ -84,9 +134,9 @@ In this section, you create a JavaScript application that sends events to an eve
84134
console.log("Error occurred: ", err);
85135
});
86136
```
87-
1. In the code, use real values to replace the following:
88-
* `EVENT HUBS NAMESPACE CONNECTION STRING`
89-
* `EVENT HUB NAME`
137+
138+
---
139+
90140
1. Run `node send.js` to execute this file. This command sends a batch of three events to your event hub.
91141
1. In the Azure portal, verify that the event hub has received the messages. Refresh the page to update the chart. It might take a few seconds for it to show that the messages have been received.
92142

@@ -112,15 +162,136 @@ To create an Azure storage account and a blob container in it, do the following
112162
113163
1. [Create an Azure storage account](../storage/common/storage-account-create.md?tabs=azure-portal)
114164
2. [Create a blob container in the storage account](../storage/blobs/storage-quickstart-blobs-portal.md#create-a-container)
115-
3. [Get the connection string to the storage account](../storage/common/storage-configure-connection-string.md)
165+
3. Authenticate to the blob container
166+
167+
## [Passwordless (Recommended)](#tab/passwordless)
168+
169+
[!INCLUDE [event-hub-storage-assign-roles](../../includes/passwordless/event-hub/event-hub-storage-assign-roles.md)]
170+
171+
## [Connection String](#tab/connection-string)
172+
173+
[Get the connection string to the storage account](../storage/common/storage-configure-connection-string.md)
174+
175+
Note the connection string and the container name. You'll use them in the receive code.
176+
177+
---
178+
179+
### Install the npm packages to receive events
180+
181+
For the receiving side, you need to install two more packages. In this quickstart, you use Azure Blob storage to persist checkpoints so that the program doesn't read the events that it has already read. It performs metadata checkpoints on received messages at regular intervals in a blob. This approach makes it easy to continue receiving messages later from where you left off.
182+
183+
### [Passwordless (Recommended)](#tab/passwordless)
184+
185+
Run these commands:
186+
187+
```shell
188+
npm install @azure/storage-blob
189+
npm install @azure/eventhubs-checkpointstore-blob
190+
npm install @azure/identity
191+
```
192+
193+
### [Connection String](#tab/connection-string)
194+
195+
Run these commands:
196+
197+
```shell
198+
npm install @azure/storage-blob
199+
npm install @azure/eventhubs-checkpointstore-blob
200+
```
116201
117-
Be sure to record the connection string and container name for later use in the receive code.
202+
---
118203
119204
### Write code to receive events
120205
121206
1. Open your favorite editor, such as [Visual Studio Code](https://code.visualstudio.com).
122207
1. Create a file called *receive.js*, and paste the following code into it:
123208
209+
### [Passwordless (Recommended)](#tab/passwordless)
210+
211+
In the code, use real values to replace the following placeholders:
212+
- `EVENT HUBS RESOURCE NAME`
213+
- `EVENT HUB NAME`
214+
- `STORAGE ACCOUNT NAME`
215+
- `STORAGE CONTAINER NAME`
216+
217+
```javascript
218+
const { DefaultAzureCredential } = require("@azure/identity");
219+
const { EventHubConsumerClient, earliestEventPosition } = require("@azure/event-hubs");
220+
const { ContainerClient } = require("@azure/storage-blob");
221+
const { BlobCheckpointStore } = require("@azure/eventhubs-checkpointstore-blob");
222+
223+
// Event hubs
224+
const eventHubsResourceName = "EVENT HUBS RESOURCE NAME";
225+
const fullyQualifiedNamespace = `${eventHubsResourceName}.servicebus.windows.net`;
226+
const eventHubName = "EVENT HUB NAME";
227+
const consumerGroup = "$Default"; // name of the default consumer group
228+
229+
// Azure Storage
230+
const storageAccountName = "STORAGE ACCOUNT NAME";
231+
const storageContainerName = "STORAGE CONTAINER NAME";
232+
const baseUrl = `https://${storageAccountName}.blob.core.windows.net`;
233+
234+
// Azure Identity - passwordless authentication
235+
const credential = new DefaultAzureCredential();
236+
237+
async function main() {
238+
239+
// Create a blob container client and a blob checkpoint store using the client.
240+
const containerClient = new ContainerClient(
241+
`${baseUrl}/${storageContainerName}`,
242+
credential
243+
);
244+
const checkpointStore = new BlobCheckpointStore(containerClient);
245+
246+
// Create a consumer client for the event hub by specifying the checkpoint store.
247+
const consumerClient = new EventHubConsumerClient(consumerGroup, fullyQualifiedNamespace, eventHubName, credential, checkpointStore);
248+
249+
// Subscribe to the events, and specify handlers for processing the events and errors.
250+
const subscription = consumerClient.subscribe({
251+
processEvents: async (events, context) => {
252+
if (events.length === 0) {
253+
console.log(`No events received within wait time. Waiting for next interval`);
254+
return;
255+
}
256+
257+
for (const event of events) {
258+
console.log(`Received event: '${event.body}' from partition: '${context.partitionId}' and consumer group: '${context.consumerGroup}'`);
259+
}
260+
// Update the checkpoint.
261+
await context.updateCheckpoint(events[events.length - 1]);
262+
},
263+
264+
processError: async (err, context) => {
265+
console.log(`Error : ${err}`);
266+
}
267+
},
268+
{ startPosition: earliestEventPosition }
269+
);
270+
271+
// After 30 seconds, stop processing.
272+
await new Promise((resolve) => {
273+
setTimeout(async () => {
274+
await subscription.close();
275+
await consumerClient.close();
276+
resolve();
277+
}, 30000);
278+
});
279+
}
280+
281+
main().catch((err) => {
282+
console.log("Error occurred: ", err);
283+
});
284+
```
285+
286+
### [Connection String](#tab/connection-string)
287+
288+
289+
In the code, use real values to replace the following placeholders:
290+
- `EVENT HUBS NAMESPACE CONNECTION STRING`
291+
- `EVENT HUB NAME`
292+
- `STORAGE CONNECTION STRING`
293+
- `STORAGE CONTAINER NAME`
294+
124295
```javascript
125296
const { EventHubConsumerClient, earliestEventPosition } = require("@azure/event-hubs");
126297
const { ContainerClient } = require("@azure/storage-blob");
@@ -129,8 +300,8 @@ Be sure to record the connection string and container name for later use in the
129300
const connectionString = "EVENT HUBS NAMESPACE CONNECTION STRING";
130301
const eventHubName = "EVENT HUB NAME";
131302
const consumerGroup = "$Default"; // name of the default consumer group
132-
const storageConnectionString = "AZURE STORAGE CONNECTION STRING";
133-
const containerName = "BLOB CONTAINER NAME";
303+
const storageConnectionString = "STORAGE CONNECTION STRING";
304+
const containerName = "STORAGE CONTAINER NAME";
134305
135306
async function main() {
136307
// Create a blob container client and a blob checkpoint store using the client.
@@ -176,11 +347,10 @@ Be sure to record the connection string and container name for later use in the
176347
console.log("Error occurred: ", err);
177348
});
178349
```
179-
1. In the code, use real values to replace the following values:
180-
- `EVENT HUBS NAMESPACE CONNECTION STRING`
181-
- `EVENT HUB NAME`
182-
- `AZURE STORAGE CONNECTION STRING`
183-
- `BLOB CONTAINER NAME`
350+
351+
---
352+
353+
184354
1. Run `node receive.js` in a command prompt to execute this file. The window should display messages about received events.
185355
186356
```
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
---
2+
title: "include file"
3+
description: "include file"
4+
services: storage
5+
author: alexwolfmsft
6+
ms.service: storage
7+
ms.topic: include
8+
ms.date: 09/09/2022
9+
ms.author: alexwolf
10+
ms.custom: include file
11+
---
12+
13+
When developing locally, make sure that the user account that connects to Azure Event Hubs has the correct permissions. You'll need the [Azure Event Hubs Data Owner](../../../articles/role-based-access-control/built-in-roles.md#azure-event-hubs-data-owner) role in order to send and receive messages. To assign yourself this role, you'll need the User Access Administrator role, or another role that includes the `Microsoft.Authorization/roleAssignments/write` action. You can assign Azure RBAC roles to a user using the Azure portal, Azure CLI, or Azure PowerShell. Learn more about the available scopes for role assignments on the [scope overview](/azure/role-based-access-control/scope-overview) page.
14+
15+
The following example assigns the `Azure Event Hubs Data Owner` role to your user account, which provides full access to Azure Event Hubs resources. In a real scenario, follow the [Principle of Least Privilege](/azure/active-directory/develop/secure-least-privileged-access) to give users only the minimum permissions needed for a more secure production environment.
16+
17+
### Azure built-in roles for Azure Event Hubs
18+
For Azure Event Hubs, the management of namespaces and all related resources through the Azure portal and the Azure resource management API is already protected using the Azure RBAC model. Azure provides the below Azure built-in roles for authorizing access to an Event Hubs namespace:
19+
20+
- [Azure Event Hubs Data Owner](../../../articles/role-based-access-control/built-in-roles.md#azure-event-hubs-data-owner): Enables data access to Event Hubs namespace and its entities (queues, topics, subscriptions, and filters)
21+
- [Azure Event Hubs Data Sender](../../../articles/role-based-access-control/built-in-roles.md#azure-event-hubs-data-sender): Use this role to give the sender access to Event Hubs namespace and its entities.
22+
- [Azure Event Hubs Data Receiver](../../../articles/role-based-access-control/built-in-roles.md#azure-event-hubs-data-receiver): Use this role to give the receiver access to Event Hubs namespace and its entities.
23+
24+
If you want to create a custom role, see [Rights required for Event Hubs operations](../../../articles/service-bus-messaging/service-bus-sas.md#rights-required-for-service-bus-operations).
25+
26+
> [!IMPORTANT]
27+
> In most cases, it will take a minute or two for the role assignment to propagate in Azure. In rare cases, it may take up to eight minutes. If you receive authentication errors when you first run your code, wait a few moments and try again.
28+
29+
### [Azure portal](#tab/roles-azure-portal)
30+
31+
1. In the Azure portal, locate your Event Hubs namespace using the main search bar or left navigation.
32+
33+
2. On the overview page, select **Access control (IAM)** from the left-hand menu.
34+
35+
3. On the **Access control (IAM)** page, select the **Role assignments** tab.
36+
37+
4. Select **+ Add** from the top menu and then **Add role assignment** from the resulting drop-down menu.
38+
39+
:::image type="content" source="media/event-hub-assign-roles/add-role.png" alt-text="A screenshot showing how to assign a role.":::
40+
41+
5. Use the search box to filter the results to the desired role. For this example, search for `Azure Event Hubs Data Owner` and select the matching result. Then choose **Next**.
42+
43+
6. Under **Assign access to**, select **User, group, or service principal**, and then choose **+ Select members**.
44+
45+
7. In the dialog, search for your Azure AD username (usually your *user@domain* email address) and then choose **Select** at the bottom of the dialog.
46+
47+
8. Select **Review + assign** to go to the final page, and then **Review + assign** again to complete the process.
48+
49+
### [Azure CLI](#tab/roles-azure-cli)
50+
51+
To assign a role at the resource level using the Azure CLI, you first must retrieve the resource ID using the `az servicebus namespace show` command. You can filter the output properties using the `--query` parameter.
52+
53+
```azurecli
54+
az servicebus namespace show -g '<your-event-hub-resource-group>' -n '<your-event-hub-name> --query id
55+
```
56+
57+
Copy the output `Id` from the preceding command. You can then assign roles using the [az role](/cli/azure/role) command of the Azure CLI.
58+
59+
```azurecli
60+
az role assignment create --assignee "<user@domain>" \
61+
--role "Azure Event Hubs Data Owner" \
62+
--scope "<your-resource-id>"
63+
```
64+
65+
---

0 commit comments

Comments
 (0)