Skip to content

Commit aca4a50

Browse files
authored
Merge pull request #132910 from baanders/10-7-authenticate
ADT- Azure.Identity for auth
2 parents 86e5c71 + a032713 commit aca4a50

File tree

1 file changed

+79
-128
lines changed

1 file changed

+79
-128
lines changed

articles/digital-twins/how-to-authenticate-client.md

Lines changed: 79 additions & 128 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,9 @@ titleSuffix: Azure Digital Twins
55
description: See how to write authentication code in a client application
66
author: baanders
77
ms.author: baanders # Microsoft employees only
8-
ms.date: 4/22/2020
8+
ms.date: 10/7/2020
99
ms.topic: how-to
1010
ms.service: digital-twins
11-
ms.custom: devx-track-js
1211

1312
# Optional fields. Don't forget to remove # if you need a field.
1413
# ms.custom: can-be-multiple-comma-separated
@@ -18,60 +17,66 @@ ms.custom: devx-track-js
1817

1918
# Write client app authentication code
2019

21-
After you [set up an Azure Digital Twins instance and authentication](how-to-set-up-instance-portal.md), you can create a client application that you will use to interact with the instance. Once you have set up a starter client project, this article shows you **how to write code in that client app to authenticate it** against the Azure Digital Twins instance.
20+
After you [set up an Azure Digital Twins instance and authentication](how-to-set-up-instance-portal.md), you can create a client application that you will use to interact with the instance. Once you have set up a starter client project, you'll need to **write code in that client app to authenticate it** against the Azure Digital Twins instance.
2221

23-
There are two approaches to sample code in this article. You can use the one that's right for you, depending on your language of choice:
24-
* The first section of sample code uses the Azure Digital Twins .NET (C#) SDK. The SDK is part of the Azure SDK for .NET, and is located here: [*Azure IoT Digital Twin client library for .NET*](https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/digitaltwins/Azure.DigitalTwins.Core). There are also supported SDKs for [Java](https://search.maven.org/artifact/com.azure/azure-digitaltwins-core/1.0.0-beta.1/jar ) and [JavaScript](https://www.npmjs.com/package/@azure/digital-twins/v/1.0.0-preview.1), which can be used in a similar way.
25-
* The second section of sample code is for users not using a provided SDK, and instead using AutoRest-generated SDKs in other languages. For more information on this strategy, see [*How-to: Create custom SDKs for Azure Digital Twins with AutoRest*](how-to-create-custom-sdks.md).
22+
Azure Digital Twins performs authentication using [Azure AD Security Tokens based on OAUTH 2.0](../active-directory/develop/security-tokens.md#json-web-tokens-jwts-and-claims). To authenticate your SDK, you'll need to get a bearer token with the right permissions to Azure Digital Twins, and pass it along with your API calls.
2623

27-
You can also read more about the APIs and SDKs for Azure Digital Twins in [*How-to: Use the Azure Digital Twins APIs and SDKs*](how-to-use-apis-sdks.md).
24+
This article describes how to obtain credentials using the `Azure.Identity` client library. While this article shows code examples in C#, such as what you'd write for the [.NET (C#) SDK](https://www.nuget.org/packages/Azure.DigitalTwins.Core), you can use a version of `Azure.Identity` regardless of what SDK you're using (for more on the SDKs available for Azure Digital Twins, see [*How-to: Use the Azure Digital Twins APIs and SDKs*](how-to-use-apis-sdks.md)).
2825

2926
## Prerequisites
3027

3128
First, complete the setup steps in [*How-to: Set up an instance and authentication*](how-to-set-up-instance-portal.md). This will ensure you have an Azure Digital Twins instance, your user has access permissions, and you've set up permissions for client applications. After all this setup, you are ready to write client app code.
3229

3330
To proceed, you will need a client app project in which you write your code. If you don't already have a client app project set up, create a basic project in your language of choice to use with this tutorial.
3431

35-
## Authentication and client creation: .NET (C#) SDK
32+
## Common authentication methods with Azure.Identity
3633

37-
This section shows an example in C# for using the provided .NET SDK.
34+
`Azure.Identity` is a client library that provides several credential-obtaining methods that you can use to get a bearer token and authenticate with your SDK. Although this article gives examples in C#, you can view `Azure.Identity` for several languages, including...
35+
* [.NET (C#)](https://docs.microsoft.com/dotnet/api/azure.identity?view=azure-dotnet&preserve-view=true)
36+
* [Java](https://docs.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable&preserve-view=true)
37+
* [JavaScript](https://docs.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest&preserve-view=true)
38+
* [Python](https://docs.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python&preserve-view=true)
3839

39-
First, include the following packages in your project in order to use the .NET SDK and authentication tools for this how-to:
40-
* `Azure.DigitalTwins.Core`
41-
* `Azure.Identity`
40+
Three common credential-obtaining methods in `Azure.Identity` are:
41+
* [DefaultAzureCredential](https://docs.microsoft.com/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet&preserve-view=true) provides a default `TokenCredential` authentication flow for applications that will be deployed to Azure, and is **the recommended choice for local development**. It also can be enabled to try the other two methods recommended in this article; it wraps `ManagedIdentityCredential` and can access `InteractiveBrowserCredential` with a configuration variable.
42+
* [ManagedIdentityCredential](https://docs.microsoft.com/dotnet/api/azure.identity.managedidentitycredential?view=azure-dotnet&preserve-view=true) works great in cases where you need [managed identities (MSI)](../active-directory/managed-identities-azure-resources/overview.md), and is a good candidate for working with Azure Functions and deploying to Azure services.
43+
* [InteractiveBrowserCredential](https://docs.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential?view=azure-dotnet&preserve-view=true) is intended for interactive applications, and can be used to create an authenticated SDK client
44+
45+
The following example shows how to use each of these with the .NET (C#) SDK.
46+
47+
## Authentication examples: .NET (C#) SDK
48+
49+
This section shows an example in C# for using the provided .NET SDK to write authentication code.
4250

43-
Depending on your tools of choice, you can include the packages using the Visual Studio package manager or the `dotnet` command line tool.
51+
First, include the SDK package `Azure.DigitalTwins.Core` and the `Azure.Identity` package in your project. Depending on your tools of choice, you can include the packages using the Visual Studio package manager or the `dotnet` command line tool.
4452

45-
You'll also need the following using statements:
53+
You'll also need to add the following using statements to your project code:
4654

4755
```csharp
4856
using Azure.Identity;
4957
using Azure.DigitalTwins.Core;
5058
```
51-
To authenticate with the .NET SDK, use one of the credential-obtaining methods that are defined in the [Azure.Identity](https://docs.microsoft.com/dotnet/api/azure.identity?view=azure-dotnet&preserve-view=true) library. Here are two that are commonly used (even together in the same application):
5259

53-
* [InteractiveBrowserCredential](https://docs.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential?view=azure-dotnet&preserve-view=true) is intended for interactive applications, and can be used to create an authenticated SDK client
54-
* [ManagedIdentityCredential](https://docs.microsoft.com/dotnet/api/azure.identity.managedidentitycredential?view=azure-dotnet&preserve-view=true) works great in cases where you need managed identities (MSI), and is a good candidate for working with Azure Functions
60+
Then, add code to obtain credentials using one of the methods in `Azure.Identity`.
5561

56-
### InteractiveBrowserCredential method
57-
The [InteractiveBrowserCredential](https://docs.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential?view=azure-dotnet&preserve-view=true) method is intended for interactive applications and will bring up a web browser for authentication.
62+
### DefaultAzureCredential method
63+
64+
[DefaultAzureCredential](https://docs.microsoft.com/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet&preserve-view=true) provides a default `TokenCredential` authentication flow for applications that will be deployed to Azure, and is **the recommended choice for local development**.
5865

59-
To use the interactive browser credentials to create an authenticated SDK client, add this code:
66+
To use the default Azure credentials, you'll need the Azure Digital Twins instance's URL ([instructions to find](how-to-set-up-instance-portal.md#verify-success-and-collect-important-values)).
67+
68+
Here is a code sample to add a `DefaultAzureCredential` to your project:
6069

6170
```csharp
62-
// Your client / app registration ID
63-
private static string clientId = "<your-client-ID>";
64-
// Your tenant / directory ID
65-
private static string tenantId = "<your-tenant-ID>";
6671
// The URL of your instance, starting with the protocol (https://)
67-
private static string adtInstanceUrl = "<your-Azure-Digital-Twins-instance-URL>";
72+
private static string adtInstanceUrl = "https://<your-Azure-Digital-Twins-instance-URL>";
6873

6974
//...
7075
7176
DigitalTwinsClient client;
7277
try
7378
{
74-
var credential = new InteractiveBrowserCredential(tenantId, clientId);
79+
var credential = new DefaultAzureCredential();
7580
client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential);
7681
} catch(Exception e)
7782
{
@@ -80,11 +85,14 @@ try
8085
}
8186
```
8287

83-
>[!NOTE]
84-
> While you can place the client ID, tenant ID and instance URL directly into the code as shown above, it's a good idea to have your code get these values from a configuration file or environment variable instead.
85-
8688
### ManagedIdentityCredential method
87-
The [ManagedIdentityCredential](https://docs.microsoft.com/dotnet/api/azure.identity.managedidentitycredential?view=azure-dotnet&preserve-view=true) method works great in cases where you need [managed identities (MSI)](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview)—for example, when working with Azure Functions.
89+
90+
The [ManagedIdentityCredential](https://docs.microsoft.com/dotnet/api/azure.identity.managedidentitycredential?view=azure-dotnet&preserve-view=true) method works great in cases where you need [managed identities (MSI)](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview)—for example, when working with Azure Functions.
91+
92+
This means that you may use `ManagedIdentityCredential` in the same project as `DefaultAzureCredential` or `InteractiveBrowserCredential`, to authenticate a different part of the project.
93+
94+
To use the default Azure credentials, you'll need the Azure Digital Twins instance's URL ([instructions to find](how-to-set-up-instance-portal.md#verify-success-and-collect-important-values)).
95+
8896
In an Azure function, you can use the managed identity credentials like this:
8997

9098
```csharp
@@ -94,116 +102,59 @@ DigitalTwinsClientOptions opts =
94102
client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred, opts);
95103
```
96104

105+
### InteractiveBrowserCredential method
106+
107+
The [InteractiveBrowserCredential](https://docs.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential?view=azure-dotnet&preserve-view=true) method is intended for interactive applications and will bring up a web browser for authentication. You can use this instead of `DefaultAzureCredential` in cases where you require interactive authentication.
108+
109+
To use the interactive browser credentials, you will need an **app registration** that has permissions to the Azure Digital Twins APIs. For steps on how to set up this app registration, see the [*Set up access permissions for client applications*](how-to-set-up-instance-portal.md#set-up-access-permissions-for-client-applications) section of *How-to: Set up an instance and authentication*. Once the app registration is set up, you'll need...
110+
* the app registration's *Application (client) ID*
111+
* the app registration's *Directory (tenant) ID*
112+
* the Azure Digital Twins instance's URL ([instructions to find](how-to-set-up-instance-portal.md#verify-success-and-collect-important-values))
113+
114+
Here is an example of the code to create an authenticated SDK client using `InteractiveBrowserCredential`.
115+
116+
```csharp
117+
// Your client / app registration ID
118+
private static string clientId = "<your-client-ID>";
119+
// Your tenant / directory ID
120+
private static string tenantId = "<your-tenant-ID>";
121+
// The URL of your instance, starting with the protocol (https://)
122+
private static string adtInstanceUrl = "https://<your-Azure-Digital-Twins-instance-URL>";
123+
124+
//...
125+
126+
DigitalTwinsClient client;
127+
try
128+
{
129+
var credential = new InteractiveBrowserCredential(tenantId, clientId);
130+
client = new DigitalTwinsClient(new Uri(adtInstanceUrl), credential);
131+
} catch(Exception e)
132+
{
133+
Console.WriteLine($"Authentication or client creation error: {e.Message}");
134+
Environment.Exit(0);
135+
}
136+
```
137+
138+
>[!NOTE]
139+
> While you can place the client ID, tenant ID and instance URL directly into the code as shown above, it's a good idea to have your code get these values from a configuration file or environment variable instead.
140+
141+
#### Other notes about authenticating Azure Functions
142+
97143
See [*How-to: Set up an Azure function for processing data*](how-to-create-azure-function.md) for a more complete example that explains some of the important configuration choices in the context of functions.
98144

99145
Also, to use authentication in a function, remember to:
100146
* [Enable managed identity](https://docs.microsoft.com/azure/app-service/overview-managed-identity?tabs=dotnet)
101147
* Use [environment variables](https://docs.microsoft.com/sandbox/functions-recipes/environment-variables?tabs=csharp) as appropriate
102148
* Assign permissions to the functions app that enable it to access the Digital Twins APIs. For more information on Azure Functions processes, see [*How-to: Set up an Azure function for processing data*](how-to-create-azure-function.md).
103149

104-
## Authentication with an AutoRest-generated SDK
105-
106-
If you are not using one of the provided SDKs (.NET, Java, JavaScript), you may opt to build an SDK library in a language of your choice, as described in [*How-to: Create custom SDKs for Azure Digital Twins with AutoRest*](how-to-create-custom-sdks.md).
107-
108-
This section explains how to authenticate in that case.
109-
110-
### Prerequisites
111-
112-
First, you should complete the steps to create a custom SDK with AutoRest, using the steps in [*How-to: Create custom SDKs for Azure Digital Twins with AutoRest*](how-to-create-custom-sdks.md).
113-
114-
This example uses a Typescript SDK generated with AutoRest. As a result, it also requires:
115-
* [msal-js](https://github.com/AzureAD/microsoft-authentication-library-for-js)
116-
* [ms-rest-js](https://github.com/Azure/ms-rest-js)
117-
118-
### Minimal authentication code sample
119-
120-
To authenticate an app with Azure services, you can use the following minimal code within your client app.
121-
122-
You will need your *Application (client) ID* and *Directory (tenant) ID* from earlier, as well as the URL of your Azure Digital Twins instance.
123-
124-
> [!TIP]
125-
> The Azure Digital Twins instance's URL is made by adding *https://* to the beginning of your Azure Digital Twins instance's *hostName*. To see the *hostName*, along with all the properties of your instance, you can run `az dt show --dt-name <your-Azure-Digital-Twins-instance>`. You can use the `az account show --query tenantId` command to see your *Directory (tenant) ID*.
126-
127-
```javascript
128-
import * as Msal from "msal";
129-
import { TokenCredentials } from "@azure/ms-rest-js";
130-
// Autorest-generated SDK
131-
import { AzureDigitalTwinsAPI } from './azureDigitalTwinsAPI';
132-
133-
// Client / app registration ID
134-
var ClientId = "<your-client-ID>";
135-
// Azure tenant / directory ID
136-
var TenantId = "<your-tenant-ID>";
137-
// URL of the Azure Digital Twins instance
138-
var AdtInstanceUrl = "<your-instance-URL>";
139-
140-
var AdtAppId = "https://digitaltwins.azure.net";
141-
142-
let client = null;
143-
144-
export async function login() {
145-
146-
const msalConfig = {
147-
auth: {
148-
clientId: ClientId,
149-
redirectUri: "http://localhost:3000",
150-
authority: "https://login.microsoftonline.com/"+TenantId
151-
}
152-
};
153-
154-
const msalInstance = new Msal.UserAgentApplication(msalConfig);
155-
156-
msalInstance.handleRedirectCallback((error, response) => {
157-
// handle redirect response or error
158-
});
159-
160-
var loginRequest = {
161-
scopes: [AdtAppId + "/.default"]
162-
};
163-
164-
try {
165-
await msalInstance.loginPopup(loginRequest)
166-
var accessToken;
167-
// if the user is already logged in you can acquire a token
168-
if (msalInstance.getAccount()) {
169-
var tokenRequest = {
170-
scopes: [AdtAppId + "/.default"]
171-
};
172-
try {
173-
const response = await msalInstance.acquireTokenSilent(tokenRequest);
174-
accessToken = response.accessToken;
175-
} catch (err) {
176-
if (err.name === "InteractionRequiredAuthError") {
177-
const response = await msalInstance.acquireTokenPopup(tokenRequest)
178-
accessToken = response.accessToken;
179-
}
180-
}
181-
}
182-
if (accessToken!=null)
183-
{
184-
var tokenCredentials = new TokenCredentials(accessToken);
185-
186-
// Add token and server URL to service instance
187-
const clientConfig = {
188-
baseUri: AdtInstanceUrl
189-
};
190-
client = new AzureDigitalTwinsAPI(tokenCredentials, clientConfig);
191-
appDataStore.client = client;
192-
}
193-
} catch (err) {
194-
...
195-
}
196-
}
197-
```
198-
199-
Note again that where the code above places the client ID, tenant ID and instance URL directly into the code for simplicity, it's a good idea to have your code get these values from a configuration file or environment variable instead.
150+
## Other credential methods
200151

201-
MSAL has many more options you can use, to implement things like caching and other authentication flows. For more information on this, see [*Overview of Microsoft Authentication Library (MSAL)*](../active-directory/develop/msal-overview.md).
152+
If the highlighted authentication scenarios above do not cover the needs of your app, you can explore other types of authentication offered in the [**Microsoft identity platform**](../active-directory/develop/v2-overview.md#getting-started). The documentation for this platform covers additional authentication scenarios, organized by application type.
202153

203154
## Next steps
204155

205156
Read more about how security works in Azure Digital Twins:
206157
* [*Concepts: Security for Azure Digital Twins solutions*](concepts-security.md)
207158

208159
Or, now that authentication is set up, move on to creating models in your instance:
209-
* [*How-to: Manage custom models*](how-to-manage-model.md)
160+
* [*How-to: Manage custom models*](how-to-manage-model.md)

0 commit comments

Comments
 (0)