Amazon CognitoAuthentication 拡張機能ライブラリの例 - AWS SDK for .NET

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

Amazon CognitoAuthentication 拡張機能ライブラリの例

注記

このトピックの情報は、.NET に基づくプロジェクトに固有のものです。 Framework および AWS SDK for .NET バージョン 3.3 以前。

Amazon.Extensions.CognitoAuthentication NuGet Word パッケージにある CognitoAuthentication 拡張機能ライブラリは、.NET の Amazon Cognito ユーザープールの認証プロセスを簡素化します。 Core および Xamarin デベロッパー。ライブラリはAmazon Cognito Identity プロバイダーの API の上に構築され、ユーザー認証 API コールを作成および送信します。

CognitoAuthentication 拡張機能ライブラリの使用

Amazon Cognito には、Secure Remote Password (SRP) を使用してユーザー名とパスワードを検証するための標準認証フローのいくつかの組み込みAuthFlowChallengeName値があります。認証フローの詳細については、「Amazon Cognito ユーザープール認証フロー」を参照してください。

以下の例では、これらの using ステートメントが必要になります。

// Required for all examples using System; using Amazon; using Amazon.CognitoIdentity; using Amazon.CognitoIdentityProvider; using Amazon.Extensions.CognitoAuthentication; using Amazon.Runtime; // Required for the GetS3BucketsAsync example using Amazon.S3; using Amazon.S3.Model;

基本的な認証の使用

署名付きリクエストを必要としない AnonymousAWSCredentials を使用して AmazonCognitoIdentityProviderClient を作成します。リージョンを指定する必要はありませんが、基盤となるコードはリージョンが提供されない場合 FallbackRegionFactory.GetRegionEndpoint() を呼び出します。CognitoUserPool および CognitoUser オブジェクトを作成します。ユーザーパスワードを含む StartWithSrpAuthAsyncInitiateSrpAuthRequest メソッドを呼び出します。

public static async void GetCredsAsync() { AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials()); CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider); CognitoUser user = new CognitoUser("username", "clientID", userPool, provider); InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest() { Password = "userPassword" }; AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false); accessToken = authResponse.AuthenticationResult.AccessToken; }

チャレンジを使用した認証

NewPasswordRequired や多要素認証 (MFA) などの課題に対する認証フローの継続も簡単です。唯一の要件は、 CognitoAuthentication オブジェクト、SRP のユーザーのパスワード、および次のチャレンジに必要な情報です。この情報は、ユーザーに入力を求めた後に取得されます。次のコードは、チャレンジタイプをチェックし、認証フロー中に MFA および NewPasswordRequired チャレンジに適したレスポンスを取得する方法の 1 つを示しています。

前と同じように、基本的な認証リクエストと await および AuthFlowResponse を実行します。レスポンスを受信すると、返された AuthenticationResult オブジェクトをループします。ChallengeName タイプが NEW_PASSWORD_REQUIRED の場合は、RespondToNewPasswordRequiredAsync メソッドを呼び出します。

public static async void GetCredsChallengesAsync() { AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials()); CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider); CognitoUser user = new CognitoUser("username", "clientID", userPool, provider); InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest(){ Password = "userPassword" }; AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false); while (authResponse.AuthenticationResult == null) { if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED) { Console.WriteLine("Enter your desired new password:"); string newPassword = Console.ReadLine(); authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest() { SessionID = authResponse.SessionID, NewPassword = newPassword }); accessToken = authResponse.AuthenticationResult.AccessToken; } else if (authResponse.ChallengeName == ChallengeNameType.SMS_MFA) { Console.WriteLine("Enter the MFA Code sent to your device:"); string mfaCode = Console.ReadLine(); AuthFlowResponse mfaResponse = await user.RespondToSmsMfaAuthAsync(new RespondToSmsMfaRequest() { SessionID = authResponse.SessionID, MfaCode = mfaCode }).ConfigureAwait(false); accessToken = authResponse.AuthenticationResult.AccessToken; } else { Console.WriteLine("Unrecognized authentication challenge."); accessToken = ""; break; } } if (authResponse.AuthenticationResult != null) { Console.WriteLine("User successfully authenticated."); } else { Console.WriteLine("Error in authentication process."); } }

認証後に AWS リソースを使用する

CognitoAuthentication ライブラリを使用してユーザーが認証されると、次のステップは、ユーザーに適切な AWS リソースへのアクセスを許可することです。そのためには、Amazon Cognito フェデレーテッド ID コンソールを通じて ID プールを作成する必要があります。プロバイダーとして作成した Amazon Cognito ユーザープールを、その poolID および clientID を使用して指定することにより、Amazon Cognito ユーザープールのユーザーがアカウントに接続された AWS リソースにアクセスすることを許可できます。異なるロールを指定して、認証されていないユーザーと認証されたユーザーの両方が異なるリソースにアクセスするようにもできます。これらのルールは IAM コンソールで変更できます。ここでは、ロールのアタッチされたポリシーのアクションフィールドでアクセス許可を追加または削除できます。次に、適切な ID プール、ユーザープール、Amazon Cognito ユーザー情報を使用して、さまざまな AWS リソースを呼び出すことができます。次の例は、関連付けられた ID プールのロールで許可されているさまざまな Amazon S3 バケットにアクセスする SRP で認証されたユーザーを示しています。

public async void GetS3BucketsAsync() { var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials()); CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider); CognitoUser user = new CognitoUser("username", "clientID", userPool, provider); string password = "userPassword"; AuthFlowResponse context = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = password }).ConfigureAwait(false); CognitoAWSCredentials credentials = user.GetCognitoAWSCredentials("identityPoolID", RegionEndpoint.< YourIdentityPoolRegion >); using (var client = new AmazonS3Client(credentials)) { ListBucketsResponse response = await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false); foreach (S3Bucket bucket in response.Buckets) { Console.WriteLine(bucket.BucketName); } } }

その他の認証オプション

SRP、 NewPasswordRequired、および MFA に加えて、 CognitoAuthentication 拡張機能ライブラリでは、以下の認証フローが容易になります。

  • Custom - StartWithCustomAuthAsync(InitiateCustomAuthRequest customRequest) を呼び出すことで開始する

  • RefreshToken - への呼び出しで開始する StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest)

  • SRP RefreshToken - への呼び出しで開始する StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest)

  • SRP AdminNo - への呼び出しで開始する StartWithAdminNoSrpAuthAsync(InitiateAdminNoSrpAuthRequest adminAuthRequest)

フローに応じて適切なメソッドを呼び出します。その後、各メソッド呼び出しの AuthFlowResponse オブジェクトで示されるように、ユーザーにチャレンジを表示し続けます。また、MFA チャレンジやカスタムチャレンジRespondToSmsMfaAuthAsyncなど、適切なレスポンスメソッドRespondToCustomAuthAsyncを呼び出します。