Skip to content

Commit 1fe0db8

Browse files
committed
feat(samples): Use DefaultAzureCredential in samples using app id login
1 parent d7e73a8 commit 1fe0db8

File tree

4 files changed

+21
-133
lines changed

4 files changed

+21
-133
lines changed

sdk/digitaltwins/Azure.DigitalTwins.Core/samples/DigitalTwinsClientSample/Options.cs

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,6 @@
66

77
namespace Azure.DigitalTwins.Core.Samples
88
{
9-
internal enum LoginMethod
10-
{
11-
AppId,
12-
User,
13-
};
14-
159
public class Options
1610
{
1711
[Option('a', "adtEndpoint", Required = true, HelpText = "Digital twins service endpoint")]
@@ -20,9 +14,6 @@ public class Options
2014
[Option('i', "clientId", Required = true, HelpText = "Client Id of the application Id to login, or the application Id used to log the user in.")]
2115
public string ClientId { get; set; }
2216

23-
[Option('m', "loginMethod", Required = false, Default = "AppId", HelpText = "Choose between: AppId, User.")]
24-
public string LoginMethod { get; set; }
25-
2617
[Option('t', "tenantId", Required = true, HelpText = "Application tenant Id")]
2718
public string TenantId { get; set; }
2819

@@ -31,15 +22,5 @@ public class Options
3122

3223
[Option('e', "eventHubEndpointName", Required = true, HelpText = "Event Hub endpoint linked to digital twins instance")]
3324
public string EventHubEndpointName { get; set; }
34-
35-
internal LoginMethod GetLoginMethod()
36-
{
37-
if (Enum.TryParse<LoginMethod>(LoginMethod, out LoginMethod loginMethod))
38-
{
39-
return loginMethod;
40-
}
41-
42-
return Samples.LoginMethod.AppId;
43-
}
4425
}
4526
}

sdk/digitaltwins/Azure.DigitalTwins.Core/samples/DigitalTwinsClientSample/Program.cs

Lines changed: 15 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -32,33 +32,12 @@ public static async Task Main(string[] args)
3232
Environment.Exit(1);
3333
});
3434

35-
if (options.GetLoginMethod() == LoginMethod.AppId
36-
&& string.IsNullOrWhiteSpace(options.ClientSecret))
37-
{
38-
Console.Error.WriteLine("When LoginMethod is AppId, ClientSecret parameter is required.");
39-
Console.Error.WriteLine(HelpText.AutoBuild(result, null, null));
40-
Environment.Exit(1);
41-
}
42-
43-
// Instantiate the client
44-
45-
var httpClient = new HttpClient();
46-
DigitalTwinsClient dtClient = (options.GetLoginMethod()) switch
47-
{
48-
LoginMethod.AppId => GetDigitalTwinsClient(
35+
// Instantiate the client
36+
DigitalTwinsClient dtClient = GetDigitalTwinsClient(
4937
options.TenantId,
5038
options.ClientId,
5139
options.ClientSecret,
52-
options.AdtEndpoint),
53-
54-
LoginMethod.User => GetDigitalTwinsClient(
55-
options.TenantId,
56-
options.ClientId,
57-
options.AdtEndpoint,
58-
httpClient),
59-
60-
_ => throw new Exception("Unsupported login method"),
61-
};
40+
options.AdtEndpoint);
6241

6342
// Run the samples
6443

@@ -73,75 +52,33 @@ public static async Task Main(string[] args)
7352

7453
var publishTelemetrySamples = new PublishTelemetrySamples();
7554
await publishTelemetrySamples.RunSamplesAsync(dtClient);
76-
77-
// Clean up
78-
79-
httpClient.Dispose();
8055
}
8156

8257
/// <summary>
83-
/// Illustrates how to construct a <see cref="DigitalTwinsClient"/>, using the <see cref="ClientSecretCredential"/>
58+
/// Illustrates how to construct a <see cref="DigitalTwinsClient"/>, using the <see cref="DefaultAzureCredential"/>
8459
/// implementation of <see cref="Azure.Core.TokenCredential"/>.
85-
/// </summary>
86-
/// <param name="tenantId">The Id of the tenant of the application Id.</param>
87-
/// <param name="clientId">The application Id.</param>
88-
/// <param name="clientSecret">A client secret for the application Id.</param>
60+
/// </summary>
8961
/// <param name="adtEndpoint">The endpoint of the digital twins instance.</param>
9062
private static DigitalTwinsClient GetDigitalTwinsClient(string tenantId, string clientId, string clientSecret, string adtEndpoint)
9163
{
92-
#region Snippet:DigitalTwinsSampleCreateServiceClientWithClientSecret
64+
// These environment variables are necessary for DefaultAzureCredential to use application Id and client secret to login.
65+
Environment.SetEnvironmentVariable("AZURE_CLIENT_SECRET", clientSecret);
66+
Environment.SetEnvironmentVariable("AZURE_CLIENT_ID", clientId);
67+
Environment.SetEnvironmentVariable("AZURE_TENANT_ID", tenantId);
9368

94-
// By using the ClientSecretCredential, a specified application Id can login using a
95-
// client secret.
96-
var tokenCredential = new ClientSecretCredential(
97-
tenantId,
98-
clientId,
99-
clientSecret,
100-
new TokenCredentialOptions { AuthorityHost = KnownAuthorityHosts.AzureCloud });
69+
#region Snippet:DigitalTwinsSampleCreateServiceClientWithClientSecret
10170

71+
// DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
72+
// It attempts to use multiple credential types in an order until it finds a working credential.
73+
var tokenCredential = new DefaultAzureCredential();
74+
10275
var client = new DigitalTwinsClient(
10376
new Uri(adtEndpoint),
10477
tokenCredential);
10578

10679
#endregion Snippet:DigitalTwinsSampleCreateServiceClientWithClientSecret
10780

10881
return client;
109-
}
110-
111-
/// <summary>
112-
/// Illustrates how to construct a <see cref="DigitalTwinsClient"/> including client options,
113-
/// using the <see cref="InteractiveBrowserCredential"/> implementation of <see cref="Azure.Core.TokenCredential"/>.
114-
/// </summary>
115-
/// <param name="tenantId">The Id of the tenant of the application Id.</param>
116-
/// <param name="clientId">The application Id.</param>
117-
/// <param name="adtEndpoint">The endpoint of the digital twins instance.</param>
118-
/// <param name="httpClient">An HttpClient instance for the client to use</param>
119-
private static DigitalTwinsClient GetDigitalTwinsClient(string tenantId, string clientId, string adtEndpoint, HttpClient httpClient)
120-
{
121-
#region Snippet:DigitalTwinsSampleCreateServiceClientInteractiveLogin
122-
123-
// This illustrates how to specify client options, in this case, by providing an
124-
// instance of HttpClient for the digital twins client to use.
125-
var clientOptions = new DigitalTwinsClientOptions
126-
{
127-
Transport = new HttpClientTransport(httpClient),
128-
};
129-
130-
// By using the InteractiveBrowserCredential, the current user can login using a web browser
131-
// interactively with the AAD
132-
var tokenCredential = new InteractiveBrowserCredential(
133-
tenantId,
134-
clientId,
135-
new TokenCredentialOptions { AuthorityHost = KnownAuthorityHosts.AzureCloud });
136-
137-
var client = new DigitalTwinsClient(
138-
new Uri(adtEndpoint),
139-
tokenCredential,
140-
clientOptions);
141-
142-
#endregion Snippet:DigitalTwinsSampleCreateServiceClientInteractiveLogin
143-
144-
return client;
145-
}
82+
}
14683
}
14784
}

sdk/digitaltwins/Azure.DigitalTwins.Core/samples/Readme.md

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,9 @@ In this samples, we illustrate how to use one derived class: ClientSecretCredent
3131
> To do this, use the Azure CLI command: `az dt rbac assign-role --assignee '<user-email | application-id>' --role owner -n '<your-digital-twins-instance>'`
3232
3333
```C# Snippet:DigitalTwinsSampleCreateServiceClientWithClientSecret
34-
// By using the ClientSecretCredential, a specified application Id can login using a
35-
// client secret.
36-
var tokenCredential = new ClientSecretCredential(
37-
tenantId,
38-
clientId,
39-
clientSecret,
40-
new TokenCredentialOptions { AuthorityHost = KnownAuthorityHosts.AzureCloud });
34+
// DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
35+
// It attempts to use multiple credential types in an order until it finds a working credential.
36+
var tokenCredential = new DefaultAzureCredential();
4137

4238
var client = new DigitalTwinsClient(
4339
new Uri(adtEndpoint),

sdk/digitaltwins/Azure.DigitalTwins.Core/src/DigitalTwinsClient.cs

Lines changed: 3 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,9 @@ public class DigitalTwinsClient
4343
/// </remarks>
4444
/// <example>
4545
/// <code snippet="Snippet:DigitalTwinsSampleCreateServiceClientWithClientSecret">
46-
/// // By using the ClientSecretCredential, a specified application Id can login using a
47-
/// // client secret.
48-
/// var tokenCredential = new ClientSecretCredential(
49-
/// tenantId,
50-
/// clientId,
51-
/// clientSecret,
52-
/// new TokenCredentialOptions { AuthorityHost = KnownAuthorityHosts.AzureCloud });
46+
/// // DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
47+
/// // It attempts to use multiple credential types in an order until it finds a working credential.
48+
/// var tokenCredential = new DefaultAzureCredential();
5349
///
5450
/// var client = new DigitalTwinsClient(
5551
/// new Uri(adtEndpoint),
@@ -78,28 +74,6 @@ public DigitalTwinsClient(Uri endpoint, TokenCredential credential)
7874
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/digitaltwins/Azure.DigitalTwins.Core/samples">our repo samples</see>.
7975
/// </para>
8076
/// </remarks>
81-
/// <example>
82-
/// <code snippet="Snippet:DigitalTwinsSampleCreateServiceClientInteractiveLogin">
83-
/// // This illustrates how to specify client options, in this case, by providing an
84-
/// // instance of HttpClient for the digital twins client to use.
85-
/// var clientOptions = new DigitalTwinsClientOptions
86-
/// {
87-
/// Transport = new HttpClientTransport(httpClient),
88-
/// };
89-
///
90-
/// // By using the InteractiveBrowserCredential, the current user can login using a web browser
91-
/// // interactively with the AAD
92-
/// var tokenCredential = new InteractiveBrowserCredential(
93-
/// tenantId,
94-
/// clientId,
95-
/// new TokenCredentialOptions { AuthorityHost = KnownAuthorityHosts.AzureCloud });
96-
///
97-
/// var client = new DigitalTwinsClient(
98-
/// new Uri(adtEndpoint),
99-
/// tokenCredential,
100-
/// clientOptions);
101-
/// </code>
102-
/// </example>
10377
public DigitalTwinsClient(Uri endpoint, TokenCredential credential, DigitalTwinsClientOptions options)
10478
{
10579
Argument.AssertNotNull(options, nameof(options));

0 commit comments

Comments
 (0)