Amazon CognitoAuthentication 확장 라이브러리 예제 - AWS SDK for .NET

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Amazon CognitoAuthentication 확장 라이브러리 예제

참고

이 항목의 정보는 .NET Framework 및 AWS SDK for .NET 버전 3.3 및 이전 버전을 기반으로 하는 프로젝트에만 해당됩니다.

CognitoAuthentication 확장 라이브러리는 Amazon.Extensions에서 찾을 수 있습니다. CognitoAuthentication NuGet 패키지는 .NET Core 및 Xamarin 개발자를 위한 Amazon Cognito 사용자 풀의 인증 프로세스를 간소화합니다. 이 라이브러리는 사용자 인증 API 직접 호출을 생성하고 전송하기 위해 Amazon Cognito Identity Provider API를 기반으로 하여 구축됩니다.

확장 라이브러리 사용 CognitoAuthentication

Amazon Cognito에는 표준 인증 흐름에서 SRP(Secure Remote Password)를 통해 사용자 이름과 암호를 확인할 수 있는 기본 제공 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;

기본 사용자 인증 사용

서명된 요청이 필요 없는 익명을 AmazonCognitoIdentityProviderClientAWSCredentials사용하여 앱을 만드세요. 리전을 공급할 필요가 없습니다. 리전이 제공되지 않은 경우 기본 코드가 FallbackRegionFactory.GetRegionEndpoint()를 호출합니다. CognitoUserPoolCognitoUser 객체를 생성합니다. 사용자 암호를 포함한 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; }

챌린지로 인증

MFA (Multi-Factor Authentication) NewPasswordRequired 와 같은 문제가 있는 경우에도 인증 흐름을 계속 진행하는 것도 더 간단합니다. 유일한 요구 사항은 CognitoAuthentication 개체, SRP에 대한 사용자 암호 및 다음 챌린지에 필요한 정보이며, 이 정보는 사용자에게 입력하라는 메시지를 표시한 후 획득합니다. 다음 코드는 인증 흐름 중에 인증 유형을 확인하고 MFA 및 NewPasswordRequired 챌린지에 대한 적절한 응답을 받는 한 가지 방법을 보여줍니다.

전과 같이 기본 인증 요청을 사용하고 awaitAuthFlowResponse 합니다. 응답이 반환된 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 및 clientID를 사용하여 공급자로 생성한 Amazon Cognito 사용자 풀을 지정하면, Amazon Cognito 사용자 풀 사용자가 계정에 연결된 AWS 리소스에 액세스하도록 허용할 수 있습니다. 인증되지 않은 사용자와 인증된 사용자가 서로 다른 리소스에 액세스할 수 있도록 서로 다른 역할을 지정할 수도 있습니다. 역할의 연결된 정책의 Action 필드에서 권한을 추가하거나 제거할 수 있는 IAM 콘솔에서 이러한 역할을 변경할 수 있습니다. 그런 다음 적절한 자격 증명 풀, 사용자 풀 및 Amazon Cognito 사용자 정보를 사용하여 다양한 AWS 리소스를 호출할 수 있습니다. 다음 예제에서는 연결된 자격 증명 풀의 역할이 허용하는 다양한 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와 같은 적절한 응답 메서드를 호출합니다.