

 AWS SDK for .NET V3가 유지 관리 모드로 전환되었습니다.

[AWS SDK for .NET V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html)로 마이그레이션하는 것이 좋습니다. 마이그레이션 방법에 대한 자세한 내용과 정보는 [유지 관리 모드 공지](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/)를 참조하세요.

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

# Amazon CognitoAuthentication 확장 라이브러리 예
<a name="cognito-authentication-extension"></a>

**참고**  
이 주제의 정보는 .NET Framework 및 AWS SDK for .NET 버전 3.3 이하를 기반으로 하는 프로젝트에만 해당됩니다.

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

## CognitoAuthentication 확장 라이브러리 사용
<a name="using-the-cognitoauthentication-extension-library"></a>

Amazon Cognito에는 표준 인증 흐름에서 SRP(Secure Remote Password)를 통해 사용자 이름과 암호를 확인할 수 있는 기본 제공 `AuthFlow` 및 `ChallengeName` 값이 있습니다. 인증 흐름에 대한 자세한 내용은 [Amazon Cognito 사용자 풀 인증 흐름](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html)을 참조하십시오.

다음 예제에는 다음과 같은 `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;
```

### 기본 사용자 인증 사용
<a name="use-basic-authentication"></a>

요청에 서명하지 않아도 되는 [AnonymousAWSCredentials](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Runtime/TAnonymousAWSCredentials.html)를 사용하여 [AmazonCognitoIdentityProviderClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/CognitoIdentityProvider/TCognitoIdentityProviderClient.html)를 생성합니다. 리전을 공급할 필요가 없습니다. 리전이 제공되지 않은 경우 기본 코드가 `FallbackRegionFactory.GetRegionEndpoint()`를 호출합니다. `CognitoUserPool` 및 `CognitoUser` 객체를 생성합니다. 사용자 암호를 포함한 `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;

}
```

### 챌린지로 인증
<a name="authenticate-with-challenges"></a>

NewPasswordRequired 및 Multi-Factor Authentication(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 리소스 사용
<a name="use-aws-resources-after-authentication"></a>

사용자가 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);
        }
    }
}
```

## 더 많은 인증 옵션
<a name="more-authentication-options"></a>

SRP, NewPasswordRequired 및 MFA 뿐만 아니라 CognitoAuthentication 확장 라이브러리도 다음을 위해 더 쉬운 인증 흐름을 제공합니다.
+ 사용자 지정 - `StartWithCustomAuthAsync(InitiateCustomAuthRequest customRequest)`에 대한 호출로 시작합니다.
+ RefreshToken - `StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest)`에 대한 호출로 시작합니다.
+ RefreshTokenSRP - `StartWithRefreshTokenAuthAsync(InitiateRefreshTokenAuthRequest refreshTokenRequest)`에 대한 호출로 시작합니다.
+ AdminNoSRP - `StartWithAdminNoSrpAuthAsync(InitiateAdminNoSrpAuthRequest adminAuthRequest)`에 대한 호출로 시작합니다.

원하는 흐름에 따라 적절한 메서드를 호출합니다. 그런 다음 각 메서드 호출의 `AuthFlowResponse` 객체에 제시되어 있는 챌린지로 사용자에게 프롬프트 표시를 계속합니다. 또한 MFA 챌린지에 대한 `RespondToSmsMfaAuthAsync` 및 사용자 지정 챌린지에 대한 `RespondToCustomAuthAsync`와 같은 적절한 응답 메서드를 호출합니다.