Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(samples): Use DefaultAzureCredential in samples using app id login #12535

Merged
merged 1 commit into from
Jun 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,6 @@

namespace Azure.DigitalTwins.Core.Samples
{
internal enum LoginMethod
{
AppId,
User,
};

public class Options
{
[Option('a', "adtEndpoint", Required = true, HelpText = "Digital twins service endpoint")]
Expand All @@ -20,9 +14,6 @@ public class Options
[Option('i', "clientId", Required = true, HelpText = "Client Id of the application Id to login, or the application Id used to log the user in.")]
public string ClientId { get; set; }

[Option('m', "loginMethod", Required = false, Default = "AppId", HelpText = "Choose between: AppId, User.")]
public string LoginMethod { get; set; }

[Option('t', "tenantId", Required = true, HelpText = "Application tenant Id")]
public string TenantId { get; set; }

Expand All @@ -31,15 +22,5 @@ public class Options

[Option('e', "eventHubEndpointName", Required = true, HelpText = "Event Hub endpoint linked to digital twins instance")]
public string EventHubEndpointName { get; set; }

internal LoginMethod GetLoginMethod()
{
if (Enum.TryParse<LoginMethod>(LoginMethod, out LoginMethod loginMethod))
{
return loginMethod;
}

return Samples.LoginMethod.AppId;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,33 +32,12 @@ public static async Task Main(string[] args)
Environment.Exit(1);
});

if (options.GetLoginMethod() == LoginMethod.AppId
&& string.IsNullOrWhiteSpace(options.ClientSecret))
{
Console.Error.WriteLine("When LoginMethod is AppId, ClientSecret parameter is required.");
Console.Error.WriteLine(HelpText.AutoBuild(result, null, null));
Environment.Exit(1);
}

// Instantiate the client

var httpClient = new HttpClient();
DigitalTwinsClient dtClient = (options.GetLoginMethod()) switch
{
LoginMethod.AppId => GetDigitalTwinsClient(
// Instantiate the client
DigitalTwinsClient dtClient = GetDigitalTwinsClient(
options.TenantId,
options.ClientId,
options.ClientSecret,
options.AdtEndpoint),

LoginMethod.User => GetDigitalTwinsClient(
options.TenantId,
options.ClientId,
options.AdtEndpoint,
httpClient),

_ => throw new Exception("Unsupported login method"),
};
options.AdtEndpoint);

// Run the samples

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

var publishTelemetrySamples = new PublishTelemetrySamples();
await publishTelemetrySamples.RunSamplesAsync(dtClient);

// Clean up

httpClient.Dispose();
}

/// <summary>
/// Illustrates how to construct a <see cref="DigitalTwinsClient"/>, using the <see cref="ClientSecretCredential"/>
/// Illustrates how to construct a <see cref="DigitalTwinsClient"/>, using the <see cref="DefaultAzureCredential"/>
/// implementation of <see cref="Azure.Core.TokenCredential"/>.
/// </summary>
/// <param name="tenantId">The Id of the tenant of the application Id.</param>
/// <param name="clientId">The application Id.</param>
/// <param name="clientSecret">A client secret for the application Id.</param>
/// </summary>
/// <param name="adtEndpoint">The endpoint of the digital twins instance.</param>
private static DigitalTwinsClient GetDigitalTwinsClient(string tenantId, string clientId, string clientSecret, string adtEndpoint)
{
#region Snippet:DigitalTwinsSampleCreateServiceClientWithClientSecret
// These environment variables are necessary for DefaultAzureCredential to use application Id and client secret to login.
Environment.SetEnvironmentVariable("AZURE_CLIENT_SECRET", clientSecret);
Environment.SetEnvironmentVariable("AZURE_CLIENT_ID", clientId);
Environment.SetEnvironmentVariable("AZURE_TENANT_ID", tenantId);

// By using the ClientSecretCredential, a specified application Id can login using a
// client secret.
var tokenCredential = new ClientSecretCredential(
tenantId,
clientId,
clientSecret,
new TokenCredentialOptions { AuthorityHost = KnownAuthorityHosts.AzureCloud });
#region Snippet:DigitalTwinsSampleCreateServiceClientWithClientSecret

// DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
// It attempts to use multiple credential types in an order until it finds a working credential.
var tokenCredential = new DefaultAzureCredential();

var client = new DigitalTwinsClient(
new Uri(adtEndpoint),
tokenCredential);

#endregion Snippet:DigitalTwinsSampleCreateServiceClientWithClientSecret

return client;
}

/// <summary>
/// Illustrates how to construct a <see cref="DigitalTwinsClient"/> including client options,
/// using the <see cref="InteractiveBrowserCredential"/> implementation of <see cref="Azure.Core.TokenCredential"/>.
/// </summary>
/// <param name="tenantId">The Id of the tenant of the application Id.</param>
/// <param name="clientId">The application Id.</param>
/// <param name="adtEndpoint">The endpoint of the digital twins instance.</param>
/// <param name="httpClient">An HttpClient instance for the client to use</param>
private static DigitalTwinsClient GetDigitalTwinsClient(string tenantId, string clientId, string adtEndpoint, HttpClient httpClient)
{
#region Snippet:DigitalTwinsSampleCreateServiceClientInteractiveLogin

// This illustrates how to specify client options, in this case, by providing an
// instance of HttpClient for the digital twins client to use.
var clientOptions = new DigitalTwinsClientOptions
{
Transport = new HttpClientTransport(httpClient),
};

// By using the InteractiveBrowserCredential, the current user can login using a web browser
// interactively with the AAD
var tokenCredential = new InteractiveBrowserCredential(
tenantId,
clientId,
new TokenCredentialOptions { AuthorityHost = KnownAuthorityHosts.AzureCloud });

var client = new DigitalTwinsClient(
new Uri(adtEndpoint),
tokenCredential,
clientOptions);

#endregion Snippet:DigitalTwinsSampleCreateServiceClientInteractiveLogin

return client;
}
}
}
}
10 changes: 3 additions & 7 deletions sdk/digitaltwins/Azure.DigitalTwins.Core/samples/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,9 @@ In this samples, we illustrate how to use one derived class: ClientSecretCredent
> 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>'`

```C# Snippet:DigitalTwinsSampleCreateServiceClientWithClientSecret
// By using the ClientSecretCredential, a specified application Id can login using a
// client secret.
var tokenCredential = new ClientSecretCredential(
tenantId,
clientId,
clientSecret,
new TokenCredentialOptions { AuthorityHost = KnownAuthorityHosts.AzureCloud });
// DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
// It attempts to use multiple credential types in an order until it finds a working credential.
var tokenCredential = new DefaultAzureCredential();

var client = new DigitalTwinsClient(
new Uri(adtEndpoint),
Expand Down
32 changes: 3 additions & 29 deletions sdk/digitaltwins/Azure.DigitalTwins.Core/src/DigitalTwinsClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,9 @@ public class DigitalTwinsClient
/// </remarks>
/// <example>
/// <code snippet="Snippet:DigitalTwinsSampleCreateServiceClientWithClientSecret">
/// // By using the ClientSecretCredential, a specified application Id can login using a
/// // client secret.
/// var tokenCredential = new ClientSecretCredential(
/// tenantId,
/// clientId,
/// clientSecret,
/// new TokenCredentialOptions { AuthorityHost = KnownAuthorityHosts.AzureCloud });
/// // DefaultAzureCredential supports different authentication mechanisms and determines the appropriate credential type based of the environment it is executing in.
/// // It attempts to use multiple credential types in an order until it finds a working credential.
/// var tokenCredential = new DefaultAzureCredential();
///
/// var client = new DigitalTwinsClient(
/// new Uri(adtEndpoint),
Expand Down Expand Up @@ -78,28 +74,6 @@ public DigitalTwinsClient(Uri endpoint, TokenCredential credential)
/// 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>.
/// </para>
/// </remarks>
/// <example>
/// <code snippet="Snippet:DigitalTwinsSampleCreateServiceClientInteractiveLogin">
/// // This illustrates how to specify client options, in this case, by providing an
/// // instance of HttpClient for the digital twins client to use.
/// var clientOptions = new DigitalTwinsClientOptions
/// {
/// Transport = new HttpClientTransport(httpClient),
/// };
///
/// // By using the InteractiveBrowserCredential, the current user can login using a web browser
/// // interactively with the AAD
/// var tokenCredential = new InteractiveBrowserCredential(
/// tenantId,
/// clientId,
/// new TokenCredentialOptions { AuthorityHost = KnownAuthorityHosts.AzureCloud });
///
/// var client = new DigitalTwinsClient(
/// new Uri(adtEndpoint),
/// tokenCredential,
/// clientOptions);
/// </code>
/// </example>
public DigitalTwinsClient(Uri endpoint, TokenCredential credential, DigitalTwinsClientOptions options)
{
Argument.AssertNotNull(options, nameof(options));
Expand Down