Amazon CognitoAuthentication 擴展庫示例 - AWS SDK for .NET

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

Amazon CognitoAuthentication 擴展庫示例

注意

本主題中的資訊特定於以 .NET Framework 和 3.3 AWS SDK for .NET 版及更早版本為基礎的專案。

CognitoAuthentication 擴展庫,在亞馬遜。擴展。 CognitoAuthentication NuGet 套件中,為 .NET 核心和 Xamarin 開發人員簡化 Amazon Cognito 使用者集區的身份驗證程序。該程式庫建立在 Amazon Cognito 身分識別提供者 API 之上,可建立和傳送使用者身份驗證 API 呼叫。

使用 CognitoAuthentication擴充功能程式庫

Amazon Cognito 具有標準身份驗證流程的一些內建ChallengeNameAuthFlow和值,可透過安全遠端密碼 (SRP) 驗證使用者名稱和密碼。如需有關驗證流量的詳細資訊,請參閱 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;

使用基本驗證

創建一個AmazonCognitoIdentityProviderClient使用匿名 AWSCredentials,它不需要簽名的請求。您不需要提供一個區域。如果未提供區域,基本程式碼會呼叫 FallbackRegionFactory.GetRegionEndpoint()。建立 CognitoUserPoolCognitoUser 物件。以 InitiateSrpAuthRequest 呼叫 StartWithSrpAuthAsync 的方法,其中包含使用者密碼。

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 挑戰的一種方法。

如同之前提出基本驗證請求,並且 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 聯合身分主控台建立身分集區。透過使用其 PooLid 和用戶端 ID 指定您建立為供應商的 Amazon Cognito 使用者集區,您可以允許 Amazon Cognito 使用者集區使用者存取連線到您帳戶的 AWS 資源。您也可以指定不同的角色,以啟用這兩種未經驗證及經過驗證的使用者存取不同的資源。您可以在 IAM 主控台變更這些規則,其中您可以新增或移除附加政策之角色的 Action (動作) 欄位的許可。然後,您可以使用適當的身分集區、使用者集區和 Amazon Cognito 使用者資訊撥打不同的 AWS 資源。下列範例顯示透過 SRP 驗證的使用者,存取關聯身分集區角色允許的不同 Amazon S3 儲存貯體

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、和 MFA 之外 NewPasswordRequired, CognitoAuthentication 擴充功能程式庫還提供更簡單的驗證流程,適用於:

  • 自訂 - 以呼叫 StartWithCustomAuthAsync(InitiateCustomAuthRequest customRequest) 起始

  • RefreshToken -通過電話啟動 StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest)

  • RefreshTokenSRP-通過呼叫啟動 StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest)

  • AdminNoSRP-通過呼叫啟動 StartWithAdminNoSrpAuthAsync(InitiateAdminNoSrpAuthRequest adminAuthRequest)

根據您要的流程呼叫適當的方法。然後,當每個方法呼叫的 AuthFlowResponse 物件中顯示挑戰時,繼續提示使用者挑戰的存在。同時呼叫適當的回應方法,例如 RespondToSmsMfaAuthAsync 用於 MFA 挑戰,RespondToCustomAuthAsync 用於自訂挑戰。