Amazon CognitoAuthentication 扩展库示例 - Amazon SDK for .NET
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

Amazon CognitoAuthentication 扩展库示例

注意

本主题中的信息特定于基于 .NET Framework 和 Amazon SDK for .NET 3.3 版及更低版本的项目。

CognitoAuthentication 扩展库,位于Amazon.Extensions.CognitoAuthentication NuGet 程序包中,简化了 .NET Core 和 Xamarin 开发人员的 Amazon Cognito 用户群体身份验证过程。该库基于 Amazon Cognito 身份提供商 API 构建,可创建和发送用户身份验证 API 调用。

使用 CognitoAuthentication 扩展库

Amazon Cognito 有一些适用于标准身份验证流程的内置 AuthFlowChallengeName 值,以通过安全远程密码(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;

用户基本身份验证

使用不需要已签名请求的 AnonymousAWSCredentials 创建一个 AmazonCognitoIdentityProviderClient。您无需提供一个区域,如果未提供区域,底层代码将调用 FallbackRegionFactory.GetRegionEndpoint()。创建 CognitoUserPoolCognitoUser 对象。使用包含用户密码的 StartWithSrpAuthAsync 调用 InitiateSrpAuthRequest 方法。

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."); } }

在进行身份验证后使用 Amazon 资源

在使用 CognitoAuthentication 库对某个用户进行身份验证后,下一步是允许该用户访问适当的 Amazon 资源。为此,您必须通过 Amazon Cognito 联合身份控制台创建一个身份池。通过将您创建的 Amazon Cognito 用户池指定为提供商并使用其 poolID 和 clientID,您可以允许您的 Amazon Cognito 用户群体用户访问连接到您账户的 Amazon 资源。您还可以指定不同的角色来支持未经身份验证的和已经过身份验证的用户访问不同的资源。您可以在 IAM 控制台中更改这些规则,其中,您可以在角色的附加策略的操作字段中添加或删除权限。然后,使用适当的身份池、用户群体和 Amazon Cognito 用户信息,您可以调用不同的 Amazon 资源。以下示例显示了使用用于访问关联的身份池的角色允许的不同 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 扩展库还提供了针对以下内容的更简单的身份验证流程:

  • 自定义- 通过调用 StartWithCustomAuthAsync(InitiateCustomAuthRequest customRequest) 启动

  • RefreshToken - 通过调用 StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest) 启动

  • RefreshTokenSRP - 通过调用 StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest) 启动

  • AdminNoSRP - 通过调用 StartWithAdminNoSrpAuthAsync(InitiateAdminNoSrpAuthRequest adminAuthRequest) 启动

根据您想要的流程调用相应的方法。然后,当质询显示在每个方法调用的 AuthFlowResponse 对象中时继续提示用户进行质询。此外,调用相应的响应方法,如适用于 MFA 质询的 RespondToSmsMfaAuthAsync 和适用于自定义质询的 RespondToCustomAuthAsync