Skip to content

Commit 7d11fe3

Browse files
author
Jill Grant
authored
Merge pull request #290913 from gsteve88/add-entra-howto-device-twins
Updated how-to device twins to include Microsoft Entra auth option
2 parents 575c31b + 4596748 commit 7d11fe3

9 files changed

+434
-39
lines changed

articles/iot-hub/how-to-device-twins.md

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -42,26 +42,6 @@ This article shows you how to develop two types of applications:
4242

4343
* **A registered device**. Some SDK calls require the device primary connection string, so make a note of the connection string.
4444

45-
* **IoT Hub service connection string**
46-
47-
In this article, you create a back-end service that adds desired properties to a device twin and then queries the identity registry to find all devices with reported properties that have been updated accordingly. Your service needs the **service connect** permission to modify desired properties of a device twin, and it needs the **registry read** permission to query the identity registry. There is no default shared access policy that contains only these two permissions, so you need to create one.
48-
49-
To create a shared access policy that grants **service connect** and **registry read** permissions and get a connection string for this policy, follow these steps:
50-
51-
1. In the Azure portal, select **Resource groups**. Select the resource group where your hub is located, and then select your hub from the list of resources.
52-
53-
1. On the left-side pane of your hub, select **Shared access policies**.
54-
55-
1. From the top menu above the list of policies, select **Add shared policy access policy**.
56-
57-
1. In the **Add shared access policy** pane on the right, enter a descriptive name for your policy, such as "serviceAndRegistryRead". Under **Permissions**, select **Registry Read** and **Service Connect**, and then select **Add**.
58-
59-
1. Select your new policy from the list of policies.
60-
61-
1. Select the copy icon for the **Primary connection string** and save the value.
62-
63-
For more information about IoT Hub shared access policies and permissions, see [Control access to IoT Hub with shared access signatures](/azure/iot-hub/authenticate-authorize-sas).
64-
6545
* If your application uses the MQTT protocol, make sure that **port 8883** is open in your firewall. The MQTT protocol communicates over port 8883. This port may be blocked in some corporate and educational network environments. For more information and ways to work around this issue, see [Connecting to IoT Hub (MQTT)](../iot/iot-mqtt-connect-to-iot-hub.md#connecting-to-iot-hub).
6646

6747
* Language SDK requirements:
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
---
2+
title: How to connect a service to IoT Hub using Microsoft Entra (.NET)
3+
titleSuffix: Azure IoT Hub
4+
description: Learn how to connect a service to IoT Hub using Microsoft Entra and the Azure IoT Hub SDK for .NET.
5+
author: kgremban
6+
ms.author: kgremban
7+
ms.service: iot-hub
8+
ms.devlang: csharp
9+
ms.topic: include
10+
ms.manager: lizross
11+
ms.date: 11/19/2024
12+
ms.custom: mqtt, devx-track-csharp, devx-track-dotnet
13+
---
14+
15+
A backend app that uses Microsoft Entra must successfully authenticate and obtain a security token credential before connecting to IoT Hub. This token is passed to a IoT Hub connection method. For general information about setting up and using Microsoft Entra for IoT Hub, see [Control access to IoT Hub by using Microsoft Entra ID](/azure/iot-hub/authenticate-authorize-azure-ad).
16+
17+
##### Configure Microsoft Entra app
18+
19+
You must set up a Microsoft Entra app that is configured for your preferred authentication credential. The app contains parameters such as client secret that are used by the backend application to authenticate. The available app authentication configurations are:
20+
21+
* Client secret
22+
* Certificate
23+
* Federated identity credential
24+
25+
Microsoft Entra apps may require specific role permissions depending on operations being performed. For example, [IoT Hub Twin Contributor](/azure/role-based-access-control/built-in-roles/internet-of-things#iot-hub-twin-contributor) is required to enable read and write access to a IoT Hub device and module twins. For more information, see [Manage access to IoT Hub by using Azure RBAC role assignment](/azure/iot-hub/authenticate-authorize-azure-ad?branch=main#manage-access-to-iot-hub-by-using-azure-rbac-role-assignment).
26+
27+
For more information about setting up a Microsoft Entra app, see [Quickstart: Register an application with the Microsoft identity platform](/entra/identity-platform/quickstart-register-app).
28+
29+
##### Authenticate using DefaultAzureCredential
30+
31+
The easiest way to use Microsoft Entra to authenticate a backend application is to use [DefaultAzureCredential](/dotnet/api/azure.identity.defaultazurecredential), but it's recommended to use a different method in a production environment including a specific `TokenCredential` or pared-down `ChainedTokenCredential`. For simplicity, this section describes authentication using `DefaultAzureCredential` and Client secret. For more information about the pros and cons of using `DefaultAzureCredential`, see [Usage guidance for DefaultAzureCredential](/dotnet/azure/sdk/authentication/credential-chains?tabs=dac#usage-guidance-for-defaultazurecredential).
32+
33+
`DefaultAzureCredential` supports different authentication mechanisms and determines the appropriate credential type based on the environment it's executing in. It attempts to use multiple credential types in an order until it finds a working credential.
34+
35+
Microsoft Entra requires these NuGet packages and corresponding `using` statements:
36+
37+
* Azure.Core
38+
* Azure.Identity
39+
40+
```csharp
41+
using Azure.Core;
42+
using Azure.Identity;
43+
```
44+
45+
In this example, Microsoft Entra app registration client secret, client ID, and tenant ID are added to environment variables. These environment variables are used by `DefaultAzureCredential` to authenticate the application. The result of a successful Microsoft Entra authentication is a security token credential that is passed to an IoT Hub connection method.
46+
47+
```csharp
48+
string clientSecretValue = "xxxxxxxxxxxxxxx";
49+
string clientID = "xxxxxxxxxxxxxx";
50+
string tenantID = "xxxxxxxxxxxxx";
51+
52+
Environment.SetEnvironmentVariable("AZURE_CLIENT_SECRET", clientSecretValue);
53+
Environment.SetEnvironmentVariable("AZURE_CLIENT_ID", clientID);
54+
Environment.SetEnvironmentVariable("AZURE_TENANT_ID", tenantID);
55+
56+
TokenCredential tokenCredential = new DefaultAzureCredential();
57+
```
58+
59+
The resulting [TokenCredential](/dotnet/api/azure.core.tokencredential) can then be passed to a connect to IoT Hub method for any SDK client that accepts Microsoft Entra credentials:
60+
61+
* [JobClient](/dotnet/api/microsoft.azure.devices.jobclient.create?#microsoft-azure-devices-jobclient-create(system-string-azure-core-tokencredential-microsoft-azure-devices-httptransportsettings))
62+
* [RegistryManager](/dotnet/api/microsoft.azure.devices.registrymanager.create?#microsoft-azure-devices-registrymanager-create(system-string-azure-core-tokencredential-microsoft-azure-devices-httptransportsettings))
63+
* [DigitalTwinClient](/dotnet/api/microsoft.azure.devices.digitaltwinclient)
64+
* [ServiceClient](/dotnet/api/microsoft.azure.devices.serviceclient.create?#microsoft-azure-devices-serviceclient-create(system-string-azure-core-tokencredential-microsoft-azure-devices-transporttype-microsoft-azure-devices-serviceclienttransportsettings-microsoft-azure-devices-serviceclientoptions))
65+
66+
In this example, the `TokenCredential` is passed to `ServiceClient.Create` to create a [ServiceClient](/dotnet/api/microsoft.azure.devices.serviceclient) connection object.
67+
68+
```csharp
69+
string hostname = "xxxxxxxxxx.azure-devices.net";
70+
using var serviceClient = ServiceClient.Create(hostname, tokenCredential, TransportType.Amqp);
71+
```
72+
73+
In this example, the `TokenCredential` is passed to `RegistryManager.Create` to create a [RegistryManager](/dotnet/api/microsoft.azure.devices.registrymanager) object.
74+
75+
```csharp
76+
string hostname = "xxxxxxxxxx.azure-devices.net";
77+
registryManager = RegistryManager.Create(hostname, tokenCredential);
78+
```
79+
80+
##### Code sample
81+
82+
For a working sample of Microsoft Entra service authentication, see [Role based authentication sample](https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/service/samples/how%20to%20guides/RoleBasedAuthenticationSample).
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
---
2+
title: How to connect a service to IoT Hub using Microsoft Entra (Java)
3+
titleSuffix: Azure IoT Hub
4+
description: Learn how to connect a service to IoT Hub using Microsoft Entra and the Azure IoT Hub SDK for Java.
5+
author: kgremban
6+
ms.author: kgremban
7+
ms.service: iot-hub
8+
ms.devlang: java
9+
ms.topic: include
10+
ms.manager: lizross
11+
ms.date: 11/19/2024
12+
---
13+
14+
A backend app that uses Microsoft Entra must successfully authenticate and obtain a security token credential before connecting to IoT Hub. This token is passed to a IoT Hub connection method. For general information about setting up and using Microsoft Entra for IoT Hub, see [Control access to IoT Hub by using Microsoft Entra ID](/azure/iot-hub/authenticate-authorize-azure-ad).
15+
16+
For an overview of Java SDK authentication, see [Azure authentication with Java and Azure Identity](/azure/developer/java/sdk/authentication/overview).
17+
18+
For simplicity, this section focuses on describing authentication using client secret.
19+
20+
##### Configure Microsoft Entra app
21+
22+
You must set up a Microsoft Entra app that is configured for your preferred authentication credential. The app contains parameters such as client secret that are used by the backend application to authenticate. The available app authentication configurations are:
23+
24+
* Client secret
25+
* Certificate
26+
* Federated identity credential
27+
28+
Microsoft Entra apps may require specific role permissions depending on operations being performed. For example, [IoT Hub Twin Contributor](/azure/role-based-access-control/built-in-roles/internet-of-things#iot-hub-twin-contributor) is required to enable read and write access to a IoT Hub device and module twins. For more information, see [Manage access to IoT Hub by using Azure RBAC role assignment](/azure/iot-hub/authenticate-authorize-azure-ad?#manage-access-to-iot-hub-by-using-azure-rbac-role-assignment).
29+
30+
For more information about setting up a Microsoft Entra app, see [Quickstart: Register an application with the Microsoft identity platform](/entra/identity-platform/quickstart-register-app).
31+
32+
##### Authenticate using DefaultAzureCredential
33+
34+
The easiest way to use Microsoft Entra to authenticate a backend application is to use [DefaultAzureCredential](/azure/developer/java/sdk/authentication/credential-chains#defaultazurecredential-overview), but it's recommended to use a different method in a production environment including a specific `TokenCredential` or pared-down `ChainedTokenCredential`.
35+
For more information about the pros and cons of using `DefaultAzureCredential`, see
36+
[Credential chains in the Azure Identity client library for Java](/azure/developer/java/sdk/authentication/credential-chains).
37+
38+
[DefaultAzureCredential](/java/api/com.azure.identity.defaultazurecredential) supports different authentication mechanisms and determines the appropriate credential type based on the environment it's executing in. It attempts to use multiple credential types in an order until it finds a working credential.
39+
40+
You can authenticate Microsoft Entra app credentials using [DefaultAzureCredentialBuilder](/java/api/com.azure.identity.defaultazurecredentialbuilder). Save connection parameters such as client secret tenantID, clientID, and client secret values as environmental variables. Once the `TokenCredential` is created, pass it to [ServiceClient](/java/api/com.azure.core.annotation.serviceclient) or other builder as the 'credential' parameter.
41+
42+
In this example, `DefaultAzureCredentialBuilder` attempts to authenticate a connection from the list described in [DefaultAzureCredential](/java/api/com.azure.identity.defaultazurecredential). The result of a successful Microsoft Entra authentication is a security token credential that is passed to a constructor such as [ServiceClient](/java/api/com.azure.core.annotation.serviceclient).
43+
44+
```java
45+
TokenCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
46+
```
47+
48+
##### Authenticate using ClientSecretCredentialBuilder
49+
50+
You can use [ClientSecretCredentialBuilder](/java/api/com.azure.identity.clientsecretcredentialbuilder) to create a credential using client secret information. If successful, this method returns a [TokenCredential](/java/api/com.azure.core.credential.tokencredential) that can be passed to [ServiceClient](/java/api/com.azure.core.annotation.serviceclient) or other builder as the 'credential' parameter.
51+
52+
In this example, Microsoft Entra app registration client secret, client ID, and tenant ID values have been added to environment variables. These environment variables are used by `ClientSecretCredentialBuilder` to build the credential.
53+
54+
```java
55+
string clientSecretValue = System.getenv("AZURE_CLIENT_SECRET");
56+
string clientID = System.getenv("AZURE_CLIENT_ID");
57+
string tenantID = System.getenv("AZURE_TENANT_ID");
58+
59+
TokenCredential credential =
60+
new ClientSecretCredentialBuilder()
61+
.tenantId(tenantID)
62+
.clientId(clientID)
63+
.clientSecret(clientSecretValue)
64+
.build();
65+
```
66+
67+
##### Other authentication classes
68+
69+
The Java SDK also includes these classes that authenticate a backend app with Microsoft Entra:
70+
71+
* [AuthorizationCodeCredential](/java/api/com.azure.identity.authorizationcodecredential)
72+
* [AzureCliCredential](/java/api/com.azure.identity.azureclicredential)
73+
* [AzureDeveloperCliCredential](/java/api/com.azure.identity.azuredeveloperclicredential)
74+
* [AzurePipelinesCredential](/java/api/com.azure.identity.azurepipelinescredential)
75+
* [ChainedTokenCredential](/java/api/com.azure.identity.chainedtokencredential)
76+
* [ClientAssertionCredential](/java/api/com.azure.identity.clientassertioncredential)
77+
* [ClientCertificateCredential](/java/api/com.azure.identity.clientcertificatecredential)
78+
* [DeviceCodeCredential](/java/api/com.azure.identity.devicecodecredential)
79+
* [EnvironmentCredential](/java/api/com.azure.identity.environmentcredential)
80+
* [InteractiveBrowserCredential](/java/api/com.azure.identity.interactivebrowsercredential)
81+
* [ManagedIdentityCredential](/java/api/com.azure.identity.managedidentitycredential)
82+
* [OnBehalfOfCredential](/java/api/com.azure.identity.onbehalfofcredential)
83+
84+
##### Code samples
85+
86+
For working samples of Microsoft Entra service authentication, see [Role based authentication sample](https://github.com/Azure/azure-iot-service-sdk-java/tree/main/service/iot-service-samples/role-based-authorization-sample).
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
---
2+
title: How to connect a service to IoT Hub using Microsoft Entra (Node.js)
3+
titleSuffix: Azure IoT Hub
4+
description: Learn how to connect a service to IoT Hub using Microsoft Entra and the Azure IoT Hub SDK for Node.js.
5+
author: kgremban
6+
ms.author: kgremban
7+
ms.service: iot-hub
8+
ms.devlang: javascript
9+
ms.topic: include
10+
ms.manager: lizross
11+
ms.date: 11/19/2024
12+
---
13+
14+
A backend app that uses Microsoft Entra must successfully authenticate and obtain a security token credential before connecting to IoT Hub. This token is passed to a IoT Hub connection method. For general information about setting up and using Microsoft Entra for IoT Hub, see [Control access to IoT Hub by using Microsoft Entra ID](/azure/iot-hub/authenticate-authorize-azure-ad).
15+
16+
For an overview of Node.js SDK authentication, see:
17+
18+
* [Getting started with user authentication on Azure](/azure/developer/javascript/how-to/with-authentication/getting-started)
19+
* [Azure Identity client library for JavaScript](/javascript/api/overview/azure/identity-readme)
20+
21+
##### Configure Microsoft Entra app
22+
23+
You must set up a Microsoft Entra app that is configured for your preferred authentication credential. The app contains parameters such as client secret that are used by the backend application to authenticate. The available app authentication configurations are:
24+
25+
* Client secret
26+
* Certificate
27+
* Federated identity credential
28+
29+
Microsoft Entra apps may require specific role permissions depending on operations being performed. For example, [IoT Hub Twin Contributor](/azure/role-based-access-control/built-in-roles/internet-of-things#iot-hub-twin-contributor) is required to enable read and write access to a IoT Hub device and module twins. For more information, see [Manage access to IoT Hub by using Azure RBAC role assignment](/azure/iot-hub/authenticate-authorize-azure-ad?#manage-access-to-iot-hub-by-using-azure-rbac-role-assignment).
30+
31+
For more information about setting up a Microsoft Entra app, see [Quickstart: Register an application with the Microsoft identity platform](/entra/identity-platform/quickstart-register-app).
32+
33+
##### Authenticate using DefaultAzureCredential
34+
35+
The easiest way to use Microsoft Entra to authenticate a backend application is to use [DefaultAzureCredential](/javascript/api/@azure/identity/defaultazurecredential), but it's recommended to use a different method in a production environment including a specific `TokenCredential` or pared-down `ChainedTokenCredential`. For simplicity, this section describes authentication using `DefaultAzureCredential` and Client secret.
36+
For more information about the pros and cons of using `DefaultAzureCredential`, see
37+
[Credential chains in the Azure Identity client library for JavaScript](/azure/developer/javascript/sdk/credential-chains#use-defaultazurecredential-for-flexibility)
38+
39+
[DefaultAzureCredential](/javascript/api/@azure/identity/defaultazurecredential) supports different authentication mechanisms and determines the appropriate credential type based on the environment it's executing in. It attempts to use multiple credential types in an order until it finds a working credential.
40+
41+
Microsoft Entra requires this package:
42+
43+
```shell
44+
npm install --save @azure/identity
45+
```
46+
47+
In this example, Microsoft Entra app registration client secret, client ID, and tenant ID have been added to environment variables. These environment variables are used by `DefaultAzureCredential` to authenticate the application. The result of a successful Microsoft Entra authentication is a security token credential that is passed to an IoT Hub connection method.
48+
49+
```javascript
50+
import { DefaultAzureCredential } from "@azure/identity";
51+
52+
// Azure SDK clients accept the credential as a parameter
53+
const credential = new DefaultAzureCredential();
54+
```
55+
56+
The resulting credential token can then be passed to [fromTokenCredential](/javascript/api/azure-iothub/registry?#azure-iothub-registry-fromtokencredential) to connect to IoT Hub for any SDK client that accepts Microsoft Entra credentials:
57+
58+
* [Registry](/javascript/api/azure-iothub/registry?#azure-iothub-registry-fromtokencredential)
59+
* [Client](/javascript/api/azure-iothub/client?#azure-iothub-client-fromtokencredential)
60+
* [JobClient](/javascript/api/azure-iothub/jobclient?#azure-iothub-jobclient-fromtokencredential)
61+
62+
`fromTokenCredential` requires two parameters:
63+
64+
* The Azure service URL - The Azure service URL should be in the format `{Your Entra domain URL}.azure-devices.net` without a `https://` prefix. For example, `MyAzureDomain.azure-devices.net`.
65+
* The Azure credential token
66+
67+
In this example, the Azure credential is obtained using `DefaultAzureCredential`. The Azure domain URL and credential are then supplied to `Registry.fromTokenCredential` to create the connection to IoT Hub.
68+
69+
```javascript
70+
const { DefaultAzureCredential } = require("@azure/identity");
71+
72+
let Registry = require('azure-iothub').Registry;
73+
74+
// Define the client secret values
75+
clientSecretValue = 'xxxxxxxxxxxxxxx'
76+
clientID = 'xxxxxxxxxxxxxx'
77+
tenantID = 'xxxxxxxxxxxxx'
78+
79+
// Set environment variables
80+
process.env['AZURE_CLIENT_SECRET'] = clientSecretValue;
81+
process.env['AZURE_CLIENT_ID'] = clientID;
82+
process.env['AZURE_TENANT_ID'] = tenantID;
83+
84+
// Acquire a credential object
85+
const credential = new DefaultAzureCredential()
86+
87+
// Create an instance of the IoTHub registry
88+
hostName = 'MyAzureDomain.azure-devices.net';
89+
let registry = Registry.fromTokenCredential(hostName,credential);
90+
```
91+
92+
##### Code samples
93+
94+
For working samples of Microsoft Entra service authentication, see [Azure identity examples](https://github.com/Azure/azure-sdk-for-js/blob/@azure/identity_4.5.0/sdk/identity/identity/samples/AzureIdentityExamples.md).

0 commit comments

Comments
 (0)