创建非交互式身份验证 .NET HDInsight 应用程序Create a non-interactive authentication .NET HDInsight application

可以在应用程序自身的标识(非交互式)或应用程序的已登录用户标识(交互式)下运行 Microsoft .NET Azure HDInsight 应用程序。You can run your Microsoft .NET Azure HDInsight application either under the application's own identity (non-interactive) or under the identity of the signed-in user of the application (interactive). 本文介绍了如何创建非交互式身份验证 .NET 应用程序以连接到 Azure 并管理 HDInsight。This article shows you how to create a non-interactive authentication .NET application to connect to Azure and manage HDInsight. 有关交互式应用程序的示例,请参阅连接到 Azure HDInsightFor a sample of an interactive application, see Connect to Azure HDInsight.

从非交互式 .NET 应用程序,需要:From your non-interactive .NET application, you need:

先决条件Prerequisites

将角色分配给 Azure AD 应用程序Assign a role to the Azure AD application

向 Azure AD 应用程序分配角色,为其授予执行操作的权限。Assign your Azure AD application a role, to grant it permissions to perform actions. 可将作用域设置为订阅、资源组或资源级别。You can set the scope at the level of the subscription, resource group, or resource. 较低级别的作用域将继承权限。The permissions are inherited to lower levels of scope. (例如,将某个应用程序添加到资源组的“读取者”角色意味着该应用程序可以读取该资源组及其中包含的所有资源。)在本教程中,将在资源组级别设置作用域。(For example, adding an application to the Reader role for a resource group means that the application can read the resource group and any resources in it.) In this tutorial, you set the scope at the resource group level. 有关详细信息,请参阅使用角色分配管理对 Azure 订阅资源的访问权限For more information, see Use role assignments to manage access to your Azure subscription resources.

将“所有者”角色添加到 Azure AD 应用程序To add the Owner role to the Azure AD application

  1. 登录到 Azure 门户Sign in to the Azure portal.
  2. 导航到具有 HDInsight 群集的资源组,在本文的后面部分中你将在该群集上运行 Hive 查询。Navigate to the resource group that has the HDInsight cluster on which you'll run your Hive query later in this article. 如果有大量资源组,可以使用筛选器查找所需的资源组。If you have a large number of resource groups, you can use the filter to find the one you want.
  3. 在“资源组”菜单中,选择“访问控制(标识和访问管理)” 。On the resource group menu, select Access control (IAM).
  4. 选择“角色分配” 选项卡以查看当前的角色分配。Select the Role assignments tab to see the current role assignments.
  5. 在页面顶部,选择“+ 添加”。 At the top of the page, select + Add.
  6. 按照说明将“所有者”角色添加到 Azure AD 应用程序。Follow the instructions to add the Owner role to your Azure AD application. 成功添加角色后,应用程序将在“所有者”角色下列出。After you successfully add the role, the application is listed under the Owner role.

开发 HDInsight 客户端应用程序Develop an HDInsight client application

  1. 创建 C# 控制台应用程序。Create a C# console application.

  2. 添加以下 NuGet 包:Add the following NuGet packages:

     Install-Package Microsoft.Azure.Common.Authentication -Pre
     Install-Package Microsoft.Azure.Management.HDInsight -Pre
     Install-Package Microsoft.Azure.Management.Resources -Pre
    
  3. 运行以下代码:Run the following code:

        using System;
        using System.Security;
        using Microsoft.Azure;
        using Microsoft.Azure.Common.Authentication;
        using Microsoft.Azure.Common.Authentication.Factories;
        using Microsoft.Azure.Common.Authentication.Models;
        using Microsoft.Azure.Management.Resources;
        using Microsoft.Azure.Management.HDInsight;
    
        namespace CreateHDICluster
        {
            internal class Program
            {
                private static HDInsightManagementClient _hdiManagementClient;
    
                private static Guid SubscriptionId = new Guid("<Enter Your Azure Subscription ID>");
                private static string tenantID = "<Enter your tenant ID (also called directory ID)>";
                private static string applicationID = "<Enter Your Application ID>";
                private static string secretKey = "<Enter the Application Secret Key>";
                private static Uri BaseUri = new Uri("https://management.chinacloudapi.cn/");
    
                private static void Main(string[] args)
                {
                    var key = new SecureString();
                    foreach (char c in secretKey) { key.AppendChar(c); }
    
                    var tokenCreds = GetTokenCloudCredentials(tenantID, applicationID, key);
                    var subCloudCredentials = GetSubscriptionCloudCredentials(tokenCreds, SubscriptionId);
    
                    var resourceManagementClient = new ResourceManagementClient(BaseUri, subCloudCredentials);
                    resourceManagementClient.Providers.Register("Microsoft.HDInsight");
    
                    _hdiManagementClient = new HDInsightManagementClient(subCloudCredentials, BaseUri);
    
                    var results = _hdiManagementClient.Clusters.List();
                    foreach (var name in results.Clusters)
                    {
                        Console.WriteLine("Cluster Name: " + name.Name);
                        Console.WriteLine("\t Cluster type: " + name.Properties.ClusterDefinition.ClusterType);
                        Console.WriteLine("\t Cluster location: " + name.Location);
                        Console.WriteLine("\t Cluster version: " + name.Properties.ClusterVersion);
                    }
                    Console.WriteLine("Press Enter to continue");
                    Console.ReadLine();
                }
    
                /// Get the access token for a service principal and provided key.          
                public static TokenCloudCredentials GetTokenCloudCredentials(string tenantId, string clientId, SecureString secretKey)
                {
                    var authFactory = new AuthenticationFactory();
                    var account = new AzureAccount { Type = AzureAccount.AccountType.ServicePrincipal, Id = clientId };
                    var env = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureChinaCloud];
                    var accessToken =
                        authFactory.Authenticate(account, env, tenantId, secretKey, ShowDialog.Never).AccessToken;
    
                    return new TokenCloudCredentials(accessToken);
                }
    
                public static SubscriptionCloudCredentials GetSubscriptionCloudCredentials(SubscriptionCloudCredentials creds, Guid subId)
                {
                    return new TokenCloudCredentials(subId.ToString(), ((TokenCloudCredentials)creds).Token);
                }
            }
        }
    

后续步骤Next steps