

第 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)。
+ 識別或建立至少一個可用於測試 SSO AWS 帳戶 的 。基於本教學課程的目的，這稱為*測試 AWS 帳戶*或僅*測試帳戶*。
+ 識別可為您測試 SSO 的 SSO *使用者*。這是將使用 SSO 和您建立的基本應用程式的人員。在本教學課程中，該人員可能是您 （開發人員） 或其他人。我們也建議 SSO 使用者在不在開發環境中的電腦上運作的設定。不過，這不是絕對必要的。
+ SSO 使用者的電腦必須安裝與您用來設定開發環境的架構相容的 .NET 架構。
+ 請確定 AWS CLI 版本 2 [已安裝](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)在 SSO 使用者的電腦上。您可以在命令提示字元或終端機`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/)中的[建立組織](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/step1.html) [IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/)。

然後，執行下列組態。

#### 設定 IAM Identity Center
<a name="w2aac15b7c41c15b3c11b7b1"></a>

1. 前往**設定**頁面。尋找**「存取入口網站 URL」**，並記錄 值以供稍後在 `sso_start_url`設定中使用。

1. 在 橫幅中 AWS 管理主控台，尋找在您啟用 SSO AWS 區域 時設定的 。這是 AWS 帳戶 ID 左側的下拉式選單。記錄區域碼以供稍後在 `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.S3`和 `AWSSDK.SecurityToken`。

```
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.IdentityManagement`和 `AWSSDK.SecurityToken`。

```
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 和 Linux 和 macOS `~/.aws`中。

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 的資源，例如檔案和資料夾。