

のバージョン 4 (V4) AWS SDK for .NET がリリースされました。

重要な変更とアプリケーションの移行については、[「移行トピック](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)

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# .NET アプリケーションのみを使用する SSO のチュートリアル
<a name="sso-tutorial-app-only"></a>

このチュートリアルでは、基本アプリケーションとテスト SSO ユーザーの SSO を有効にする方法を示します。[AWS CLI](sso-tutorial-cli-and-app.md) を使用する代わりにプログラムで一時的な SSO トークンを生成するようにアプリケーションを設定します。

このチュートリアルでは、 の SSO 機能のごく一部について説明します AWS SDK for .NET。での IAM Identity Center の使用の詳細については AWS SDK for .NET、 トピックの[背景情報](sso.md)を参照してください。そのトピックでは、特に [.NETアプリケーションのみ](sso.md#sso-generate-use-token-app-only-summary) というサブセクションにあるこのシナリオの概要説明を参照してください。

**注記**  
このチュートリアルのいくつかのステップは、 AWS Organizations や IAM Identity Center などのサービスを設定するのに役立ちます。その設定をすでに実行している場合や、コードのみに関心がある場合は、[サンプルコード](#sso-tutorial-app-only-code)のセクションまでスキップできます。

## 前提条件
<a name="sso-tutorial-app-only-prereq"></a>
+ まだの場合は、開発環境を設定します。これについては、[用のツールチェーンのインストールと設定 AWS SDK for .NET](net-dg-dev-env.md) や [入門](net-dg-config.md) などのセクションで説明しています。
+ SSO AWS アカウント のテストに使用できる 1 つ以上の を特定または作成します。このチュートリアルでは、これをテスト AWS アカウント**、または単にテストアカウント**と呼びます。
+ SSO をテストしてくれる SSO ユーザー**を指定します。これは SSO と、作成した基本的なアプリケーションを使用するユーザーです。このチュートリアルでは、あなた (開発者) でも他のユーザーでもかまいません。また、SSO ユーザーが開発環境外のコンピューターで作業するような設定もお勧めします。ただし、これは厳密には必須ではありません。
+ SSO ユーザーのコンピューターには、開発環境の設定に使用したものと互換性のある.NET Framework がインストールされている必要があります。

## セットアップ AWS
<a name="sso-tutorial-app-only-setup-aws"></a>

このセクションでは、このチュートリアルのさまざまな AWS サービスをセットアップする方法について説明します。

この設定を実行するには、まず管理者 AWS アカウント としてテストにサインインします。次に、以下の操作を実行します。

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

[Amazon S3 コンソール](https://console.aws.amazon.com/s3/home) に移動し、無害なバケットをいくつか追加します。このチュートリアルの後半では、SSO ユーザーがこれらのバケットのリストを取得します。

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

[IAM コンソール](https://console.aws.amazon.com/iam/home#/users)に移動し、IAM ユーザーを数人追加します。IAM ユーザーにアクセス権限を付与する場合は、その権限をいくつかの無害な読み取り専用権限に制限してください。このチュートリアルの後半では、SSO ユーザーがこれらの IAM ユーザーのリストを取得します。

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

[AWS Organizations コンソール](https://console.aws.amazon.com/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 アイデンティティセンター
<a name="w2aac15b7c39c15b3c11"></a>

[IAM アイデンティティセンターコンソール](https://console.aws.amazon.com/singlesignon/) に移動してSSO を有効にします。必要に応じて E メール認証を行います。詳細については、「[IAM アイデンティティセンターユーザーガイド](https://docs.aws.amazon.com/singlesignon/latest/userguide/)」の「[IAM アイデンティティセンターを有効化する](https://docs.aws.amazon.com/singlesignon/latest/userguide/step1.html)」を参照してください。

次に、以下の設定を行います。

#### IAM アイデンティティセンター を設定する
<a name="w2aac15b7c39c15b3c11b7b1"></a>

1. **[設定]** ページに移動します。**「アクセスポータル URL」** を探し、その値を後で使用できるように `sso_start_url` 設定に記録します。

1. のバナーで AWS マネジメントコンソール、SSO を有効にしたときに AWS リージョン 設定された を探します。これは AWS アカウント ID の左側にあるドロップダウンメニューです。後で使用できるようにリージョンコードを `sso_region` 設定に記録しておきます。このコードは `us-east-1` のようになります。

1. 次のように SSO ユーザーを作成します。

   1. **[ユーザー]**ページに移動します。

   1. **[ユーザーを追加]** を選択し、ユーザーの **ユーザー名**、 **メールアドレス**、 **名**、 **姓** を入力します。その後、**[Next]** を選択します。

   1. グループのページで **[次へ]** を選択し、情報を確認して **[ユーザーを追加]** を選択します。

1. 次のようにグループを作成します。

   1. **[グループ]**ページに移動します。

   1. **[グループを作成]** を選択し、グループの **[グループ名]** と **[説明]** を入力します。

   1. **[ユーザーをグループに追加]** セクションで、先ほど作成したテスト SSO ユーザーを選択します。次に、**[Create group]** (グループを作成) を選択します。

1. 次のようにアクセス権限セットを作成します。

   1. **[権限セット]** ページに移動し、**[権限セットの作成]** を選択します。

   1. **[権限セットの種類]** で **[カスタム権限セット]** を選択し、**[次へ]** を選択します。

   1. **[インラインポリシー]** を開き、次のポリシーを入力します。

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

****  

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

------

   1. このチュートリアルでは、 **権限セット名** として `SSOReadOnlyRole` を入力します。**必要に応じて説明を追加し**、 **[次へ]** を選択します。

   1. 情報を確認してから、**[Create]** (作成) を選択します。

   1. 後で使用できるように権限セットの名前を `sso_role_name` 設定に記録します。

1. **AWS アカウント**ページに移動し、以前に組織に追加した AWS アカウントを選択します。

1. そのページの 「**概要**」セクションで **アカウント ID** を探し、後で使用できるように `sso_account_id` 設定に記録しておきます。

1. **[ユーザーとグループ]** タブを選択し、**[ユーザーまたはグループの割り当て]**を選択します。

1. **[ユーザーとグループの割り当て]**ページで **[グループ]** タブを選択し、先ほど作成したグループを選択して、**[次へ]** を選択します。

1. 前に作成した権限セットを選択し、**[次へ]** を選択してから **[送信]** を選択します。設定には少し時間がかかります。

## サンプルアプリケーションを作成する
<a name="sso-tutorial-app-only-code"></a>

以下のアプリケーションを作成します。それらは、 SSO ユーザーのコンピューター上で実行されます。

### Amazon S3 バケットを一覧表示する
<a name="sso-tutorial-app-only-code-s3"></a>

`AWSSDK.S3`、 `AWSSDK.SecurityToken` に加えて NuGet パッケージ `AWSSDK.SSO`、 `AWSSDK.SSOOIDC` も含めます。

```
using System;
using System.Threading.Tasks;
using System.Diagnostics;


// 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.Programmatic_login
{
    class Program
    {
        // Requirements:
        // - An SSO profile in the SSO user's shared config file.

        // 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");

            var ssoCredentials = credentials as SSOAWSCredentials;

            ssoCredentials.Options.ClientName = "Example-SSO-App";
            ssoCredentials.Options.SsoVerificationCallback = args =>
            {
                // Launch a browser window that prompts the SSO user to complete an SSO login.
                //  This method is only invoked if the session doesn't already have a valid SSO token.
                // NOTE: Process.Start might not support launching a browser on macOS or Linux. If not,
                //       use an appropriate mechanism on those systems instead.
                Process.Start(new ProcessStartInfo
                {
                    FileName = args.VerificationUriComplete,
                    UseShellExecute = true
                });
            };
            ssoCredentials.Options.SupportsGettingNewToken = true;

            return ssoCredentials;
        }

    }

    // 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-app-only-code-iam"></a>

`AWSSDK.IdentityManagement`、 `AWSSDK.SecurityToken` に加えて NuGet パッケージ `AWSSDK.SSO`、 `AWSSDK.SSOOIDC` も含めます。

```
using System;
using System.Threading.Tasks;
using System.Diagnostics;


// 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.Programmatic_login
{
    class Program
    {
        // Requirements:
        // - An SSO profile in the SSO user's shared config file.

        // 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");

            var ssoCredentials = credentials as SSOAWSCredentials;

            ssoCredentials.Options.ClientName = "Example-SSO-App";
            ssoCredentials.Options.SsoVerificationCallback = args =>
            {
                // Launch a browser window that prompts the SSO user to complete an SSO login.
                //  This method is only invoked if the session doesn't already have a valid SSO token.
                // NOTE: Process.Start might not support launching a browser on macOS or Linux. If not,
                //       use an appropriate mechanism on those systems instead.
                Process.Start(new ProcessStartInfo
                {
                    FileName = args.VerificationUriComplete,
                    UseShellExecute = true
                });
            };
            ssoCredentials.Options.SupportsGettingNewToken = true;

            return ssoCredentials;
        }

    }

    // 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 対応プロファイル (このチュートリアルでは `my-sso-profile`) のユーザー ID ARN を表示します。

これらのアプリケーションは、[SSOAWsCredentials](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/Runtime/TSSOAWSCredentials.html) オブジェクトの [Options](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/Runtime/TSSOAWSCredentialsOptions.html) プロパティにコールバックメソッドを指定することで SSO サインインタスクを実行します。

## SSO ユーザーに指示します。
<a name="sso-tutorial-app-only-user"></a>

SSO ユーザーに E メールを確認し、SSO の招待を受け入れるように依頼します。パスワードの設定を求められます。メッセージが SSO ユーザーの受信トレイに届くまでに数分かかる場合があります。

先ほど作成したアプリケーションを SSO ユーザーに提供します。

次に、SSO ユーザーに次の操作を行わせます。

1. 共有 AWS `config`ファイルを含むフォルダが存在しない場合は、作成します。フォルダーが存在し、`.sso` という名前のサブフォルダーがある場合は、そのサブフォルダーを削除します。

   このフォルダーの場所は通常、Windows では `%USERPROFILE%\.aws`、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. 表示される Web サインインページで、サインインします。招待メッセージに記載されているユーザー名と、メッセージに応じて作成されたパスワードを使用します。

1. サインインが完了すると、アプリケーションには S3 バケットのリストが表示されます。

1. IAMアプリケーションを実行します。アプリケーションは IAM ユーザーのリストを表示します。これは、2 回目のサインインが行われなかった場合でも同様です。IAM アプリケーションは以前に作成された一時トークンを使用します。

## クリーンアップ
<a name="sso-tutorial-app-only-cleanup"></a>

このチュートリアルで作成したリソースを保持しない場合は、リソースをクリーンアップします。これらは、ファイル AWS やフォルダなどの開発環境のリソースである場合があります。