

的版本 4 (V4) 适用于 .NET 的 AWS SDK 已经发布！

有关重大更改和迁移应用程序的信息，请参阅[迁移主题](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)。

 [https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 AWS CLI 和.NET 应用程序的 SSO 教程
<a name="sso-tutorial-cli-and-app"></a>

本教程向您展示如何为基本的 .NET 应用程序和测试 SSO 用户启用 SSO。它使用生成 AWS CLI 临时 SSO 令牌，而不是以[编程方式生成](sso-tutorial-app-only.md)。

本教程向您展示了中一小部分 SSO 功能。 适用于 .NET 的 AWS SDK有关将 IAM Identity Center 与一起使用的完整详细信息 适用于 .NET 的 AWS SDK，请参阅带有[背景信息](sso.md)的主题。在该主题中，请特别参见名为[AWS CLI 和.NET 应用程序](sso.md#sso-generate-use-token-cli-and-app-summary)的小节中对此场景的总体描述。

**注意**  
本教程中的几个步骤可帮助您配置服务，例如 AWS Organizations 和 IAM Identity Center。如果您已经执行了这些配置，或者只对代码感兴趣，则可以跳到带有[示例代码](#sso-tutorial-cli-and-app-code)的部分。

## 先决条件
<a name="sso-tutorial-cli-and-app-prereq"></a>
+ 请配置您的开发环境（如果尚未配置）。在[安装和配置您的工具链 适用于 .NET 的 AWS SDK](net-dg-dev-env.md)和[入门](net-dg-config.md)之类的章节中对此进行了描述。
+ 确定或创建至少一个 AWS 账户 可用于测试 SSO 的选项。就本教程而言，名为*测试 AWS 账户*或者简称为*测试账户*。
+ 确定可以为您测试 SSO 的 *SSO 用户*。此人将使用 SSO 和您创建的基本应用程序。在本教程中，此人可能是您（开发人员）或其他人。我们还建议采用这样的设置：SSO 用户使用不在您开发环境中的计算机。但是，这并不是必要的。
+ SSO 用户的计算机必须安装与您用于设置开发环境的 .NET Framework 兼容的 .NET Framework。
+ 确保在 SSO 用户的计算机上[安装](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)了 AWS CLI 版本 2。您可以通过在命令提示符或终端中运行 `aws --version` 来检查这一点。

## 设置 AWS
<a name="sso-tutorial-cli-and-app-setup-aws"></a>

本节介绍如何为本教程设置各种 AWS 服务。

要执行此设置，请先以管理员 AWS 账户 身份登录测试。然后执行以下操作：

### Amazon S3
<a name="w2aac15b7c41c15b3b5"></a>

前往 [Amazon S3 控制台](https://console.aws.amazon.com/s3/home)并添加一些无关紧要的桶。在本教程的后面部分，SSO 用户将检索这些桶的列表。

### AWS IAM
<a name="w2aac15b7c41c15b3b7"></a>

前往 [IAM 控制台](https://console.aws.amazon.com/iam/home#/users)并添加一些 IAM 用户。如果您向 IAM 用户授予权限，请将权限限制为几个无关紧要的只读权限。在本教程的后面部分，SSO 用户将检索这些 IAM 用户的列表。

### AWS Organizations
<a name="w2aac15b7c41c15b3b9"></a>

进入 [AWS Organizations 控制台](https://console.aws.amazon.com/organizations/)并启用 Organizations。有关更多信息，请参阅 [AWS Organizations 用户指南](https://docs.aws.amazon.com/organizations/latest/userguide/)中的[创建企业](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_create.html)。

此操作将测试 AWS 账户 作为*管理账户*添加到组织。如果您还有其它测试账户，则可以邀请他们加入组织，但本教程没有必要这样做。

### IAM Identity Center
<a name="w2aac15b7c41c15b3c11"></a>

前往 [IAM Identity Center 控制台](https://console.aws.amazon.com/singlesignon/)并启用 SSO。如有必要，请执行电子邮件验证。有关更多信息，请参阅 [IAM Identity Center 用户指南](https://docs.aws.amazon.com/singlesignon/latest/userguide/)中的[启用 IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/step1.html)。

然后，执行以下配置。

#### 配置 IAM Identity Center
<a name="w2aac15b7c41c15b3c11b7b1"></a>

1. 转到**设置**页面。查找**访问门户 URL** 并记录该值供以后在 `sso_start_url` 设置中使用。

1. 在的横幅中 AWS 管理控制台，查找启用 SSO 时设置的。 AWS 区域 这是 AWS 账户 身份证左侧的下拉菜单。记录区域代码，以便以后在 `sso_region` 设置中使用。此代码将类似于 `us-east-1`。

1. 按如下方式创建 SSO 用户：

   1. 转到**用户**页面。

   1. 选择**添加用户**，然后输入用户的**用户名**、**电子邮件地址**、**名字**和**姓氏**。然后选择**下一步**。

   1. 在组页面上选择**下一步**，然后查看信息并选择**添加用户**。

1. 按如下所示创建组：

   1. 转至**组**页面。

   1. 选择**创建组**，然后输入组的**组名称**和**描述**。

   1. 在**将用户添加到组**部分中，选择您之前创建的测试 SSO 用户。选择**创建组**。

1. 按如下所示创建权限集：

   1. 转至**权限集**页面，然后选择**创建权限集**。

   1. 在**权限集类型**下，选择**自定义权限集**，然后选择**下一步**。

   1. 打开**内联策略**并输入以下策略：

------
#### [ JSON ]

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Sid": "VisualEditor0",
                  "Effect": "Allow",
                  "Action": [
                      "s3:ListAllMyBuckets",
                      "iam:ListUsers"
                  ],
                  "Resource": "*"
              }
          ]
      }
      ```

------

   1. 在本教程中，输入 `SSOReadOnlyRole` 作为**权限集名称**。如果需要，可以添加**描述**，然后选择**下一步**。

   1. 检查信息，然后选择**创建**。

   1. 记录权限集的名称，以便以后在 `sso_role_name` 设置中使用。

1. 前往**AWS 账户**页面，选择您之前添加到组织的 AWS 账户。

1. 在该页面的**概述**部分，找到**账户 ID** 并将其记录下来，以便以后在 `sso_account_id` 设置中使用。

1. 选择**用户和组**选项卡，然后选择**分配用户或组**。

1. 在**分配用户和组**页面上，选择**组**选项卡，选择您之前创建的组，然后选择**下一步**。

1. 选择您之前创建的权限集并选择**下一步**，然后选择**提交**。配置需要片刻时间。

## 创建示例应用程序
<a name="sso-tutorial-cli-and-app-code"></a>

创建以下应用程序。它们将在 SSO 用户的计算机上运行。

### 列出 Amazon S3 桶
<a name="sso-tutorial-cli-and-app-code-s3"></a>

除了`AWSSDK.SSO`和之外`AWSSDK.SSOOIDC`，还包括 NuGet 软件包`AWSSDK.SecurityToken`。`AWSSDK.S3`

```
using System;
using System.Threading.Tasks;

// NuGet packages: AWSSDK.S3, AWSSDK.SecurityToken, AWSSDK.SSO, AWSSDK.SSOOIDC
using Amazon.Runtime;
using Amazon.Runtime.CredentialManagement;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;

namespace SSOExample.S3.CLI_login
{
    class Program
    {
        // Requirements:
        // - An SSO profile in the SSO user's shared config file.
        // - An active SSO Token.
        //    If an active SSO token isn't available, the SSO user should do the following:
        //    In a terminal, the SSO user must call "aws sso login --profile my-sso-profile".

        // Class members.
        private static string profile = "my-sso-profile";
        static async Task Main(string[] args)
        {
            // Get SSO credentials from the information in the shared config file.
            var ssoCreds = LoadSsoCredentials(profile);

            // Display the caller's identity.
            var ssoProfileClient = new AmazonSecurityTokenServiceClient(ssoCreds);
            Console.WriteLine($"\nSSO Profile:\n {await ssoProfileClient.GetCallerIdentityArn()}");

            // Display a list of the account's S3 buckets.
            // The S3 client is created using the SSO credentials obtained earlier.
            var s3Client = new AmazonS3Client(ssoCreds);
            Console.WriteLine("\nGetting a list of your buckets...");
            var listResponse = await s3Client.ListBucketsAsync();
            Console.WriteLine($"Number of buckets: {listResponse.Buckets.Count}");
            foreach (S3Bucket b in listResponse.Buckets)
            {
                Console.WriteLine(b.BucketName);
            }
            Console.WriteLine();
        }

        // Method to get SSO credentials from the information in the shared config file.
        static AWSCredentials LoadSsoCredentials(string profile)
        {
            var chain = new CredentialProfileStoreChain();
            if (!chain.TryGetAWSCredentials(profile, out var credentials))
                throw new Exception($"Failed to find the {profile} profile");
            return credentials;
        }
    }

    // Class to read the caller's identity.
    public static class Extensions
    {
        public static async Task<string> GetCallerIdentityArn(this IAmazonSecurityTokenService stsClient)
        {
            var response = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest());
            return response.Arn;
        }
    }
}
```

### 列出 IAM 用户
<a name="sso-tutorial-cli-and-app-code-iam"></a>

除了`AWSSDK.SSO`和之外`AWSSDK.SSOOIDC`，还包括 NuGet 软件包`AWSSDK.SecurityToken`。`AWSSDK.IdentityManagement`

```
using System;
using System.Threading.Tasks;

// NuGet packages: AWSSDK.IdentityManagement, AWSSDK.SecurityToken, AWSSDK.SSO, AWSSDK.SSOOIDC
using Amazon.Runtime;
using Amazon.Runtime.CredentialManagement;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;

namespace SSOExample.IAM.CLI_login
{
    class Program
    {
        // Requirements:
        // - An SSO profile in the SSO user's shared config file.
        // - An active SSO Token.
        //    If an active SSO token isn't available, the SSO user should do the following:
        //    In a terminal, the SSO user must call "aws sso login --profile my-sso-profile".

        // Class members.
        private static string profile = "my-sso-profile";
        static async Task Main(string[] args)
        {
            // Get SSO credentials from the information in the shared config file.
            var ssoCreds = LoadSsoCredentials(profile);

            // Display the caller's identity.
            var ssoProfileClient = new AmazonSecurityTokenServiceClient(ssoCreds);
            Console.WriteLine($"\nSSO Profile:\n {await ssoProfileClient.GetCallerIdentityArn()}");

            // Display a list of the account's IAM users.
            // The IAM client is created using the SSO credentials obtained earlier.
            var iamClient = new AmazonIdentityManagementServiceClient(ssoCreds);
            Console.WriteLine("\nGetting a list of IAM users...");
            var listResponse = await iamClient.ListUsersAsync();
            Console.WriteLine($"Number of IAM users: {listResponse.Users.Count}");
            foreach (User u in listResponse.Users)
            {
                Console.WriteLine(u.UserName);
            }
            Console.WriteLine();
        }

        // Method to get SSO credentials from the information in the shared config file.
        static AWSCredentials LoadSsoCredentials(string profile)
        {
            var chain = new CredentialProfileStoreChain();
            if (!chain.TryGetAWSCredentials(profile, out var credentials))
                throw new Exception($"Failed to find the {profile} profile");
            return credentials;
        }
    }

    // Class to read the caller's identity.
    public static class Extensions
    {
        public static async Task<string> GetCallerIdentityArn(this IAmazonSecurityTokenService stsClient)
        {
            var response = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest());
            return response.Arn;
        }
    }
}
```

除了显示 Amazon S3 桶和 IAM 用户的列表外，这些应用程序还会显示启用 SSO 的配置文件的用户身份 ARN，在本教程中为 `my-sso-profile`。

## SSO 用户指示
<a name="sso-tutorial-cli-and-app-user"></a>

让 SSO 用户查看他们的电子邮件并接受 SSO 邀请。系统会提示他们设置密码。这封邮件可能需要几分钟才能送达 SSO 用户的收件箱。

向 SSO 用户提供您之前创建的应用程序。

然后，让 SSO 用户执行以下操作：

1. 如果包含共享 AWS `config`文件的文件夹不存在，请创建该文件夹。如果该文件夹确实存在并且有一个名为 `.sso` 的子文件夹，请删除该子文件夹。

   此文件夹的位置通常为 `%USERPROFILE%\.aws`（Windows）以及 `~/.aws`（Linux 和 macOS ）。

1. 如有必要，在该文件夹中创建共享 AWS `config`文件，然后按如下方式向其添加配置文件：

   ```
   [default]
   region = <default Region>
   
   [profile my-sso-profile]
   sso_start_url = <user portal URL recorded earlier>
   sso_region = <Region code recorded earlier>
   sso_account_id = <account ID recorded earlier>
   sso_role_name = SSOReadOnlyRole
   ```

1. 运行 Amazon S3 应用程序。出现运行时系统异常。

1. 运行以下 AWS CLI 命令：

   ```
   aws sso login --profile my-sso-profile
   ```

1. 在最终的 Web 登录页面中，登录。使用邀请消息中的用户名和为回复邮件而创建的密码。

1. 再次运行 Amazon S3 应用程序。现在，应用程序显示 S3 桶的列表。

1. 运行 IAM 应用程序。该应用程序显示 IAM 用户列表。即使没有进行第二次登录，也是如此。IAM 应用程序使用之前创建的临时令牌。

## 清理
<a name="sso-tutorial-cli-and-app-cleanup"></a>

如果您不想保留在本教程中创建的资源，请将其清理干净。这些可能是开发环境中的 AWS 资源或资源，例如文件和文件夹。