

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

# Amazon Cognito와 AWS Amplify UI를 사용하여 기존 React 애플리케이션 사용자 인증
<a name="authenticate-react-app-users-cognito-amplify-ui"></a>

*Daniel Kozhemyako, Amazon Web Services*

## 요약
<a name="authenticate-react-app-users-cognito-amplify-ui-summary"></a>

이 패턴은 AWS Amplify UI 라이브러리와 Amazon Cognitouser 풀을 사용하여 기존 프런트엔드 React 애플리케이션에 인증 기능을 추가하는 방법을 보여줍니다.

이 패턴은 Amazon Cognito를 사용하여 애플리케이션에 대한 인증, 권한 부여 및 사용자 관리를 제공합니다. 또한의 기능을 사용자 인터페이스([UI) 개발로 확장하는 오픈 소스 라이브러리인 Amplify](https://ui.docs.amplify.aws/react/getting-started/introduction) UI의 구성 요소를 사용합니다. AWS Amplify [Authenticator UI](https://ui.docs.amplify.aws/react/connected-components/authenticator/advanced) 구성 요소는 로그인 세션을 관리하고 Amazon Cognito를 통해 사용자를 인증하는 클라우드 연결 워크플로우를 실행합니다.

이 패턴을 구현한 후 사용자는 다음 보안 인증 정보 중 하나를 사용하여 로그인할 수 있습니다.
+ 사용자 이름 및 암호
+ 소셜 ID 제공업체(예: Apple, Facebook, Google, 및 Amazon)
+ SAML 2.0과 호환되거나 OpenID Connect(OIDC)와 호환되는 엔터프라이즈 ID 제공업체

**참고**  
사용자 지정 Authenticator UI 구성 요소를 생성하려면, 헤드리스 모드에서 UI 구성 요소를 실행할 수 있습니다.

## 사전 조건 및 제한 사항
<a name="authenticate-react-app-users-cognito-amplify-ui-prereqs"></a>

**사전 조건 **
+ 활성 AWS 계정
+ React 18.2.0 이상 웹 애플리케이션
+ Node.js 및 npm 6.14.4 이상, [설치](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)됨

**제한 사항 **
+ 이 패턴은 React 웹 애플리케이션에만 적용됩니다.
+ 이 패턴은 사전 빌드된 Amplify UI 구성 요소를 사용합니다. 이 솔루션에서는 사용자 지정 UI 구성 요소를 구현하는 데 필요한 단계를 다루지 않습니다.

**제품 버전**
+ Amplify UI 6.1.3 이상(Gen 1)
+ Amplify 6.0.16 이상(Gen 1)

## 아키텍처
<a name="authenticate-react-app-users-cognito-amplify-ui-architecture"></a>

**대상 아키텍처**

다음 다이어그램은 Amazon Cognito를 사용하여 React 웹 애플리케이션에 대해 사용자를 인증하는 아키텍처를 보여줍니다.

![Amazon Cognito는 React 웹 애플리케이션에 대해 사용자를 인증합니다.](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/b2cea053-6931-4404-8aa8-c623ce2024ac/images/b7f69f20-a39d-4a78-8605-7dab73c59052.png)


## 도구
<a name="authenticate-react-app-users-cognito-amplify-ui-tools"></a>

**AWS 서비스**
+ [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html)는 웹 및 모바일 앱에 대한 인증, 권한 부여 및 사용자 관리를 제공합니다.

**기타 도구**
+ [Amplify UI](https://ui.docs.amplify.aws/react/getting-started/introduction)는 클라우드에 연결할 수 있는 사용자 지정이 가능한 구성 요소를 제공하는 오픈 소스 UI 라이브러리입니다.
+ [Node.js](https://nodejs.org/en/docs/)는 확장 가능한 네트워크 애플리케이션 구축을 위해 설계된 이벤트 기반 JavaScript 런타임 환경입니다.
+ [npm](https://docs.npmjs.com/about-npm)은 Node.js 환경에서 실행되는 소프트웨어 레지스트리로, 패키지를 공유 또는 대여하고 개인 패키지의 배포를 관리하는 데 사용됩니다.

## 모범 사례
<a name="authenticate-react-app-users-cognito-amplify-ui-best-practices"></a>

새 애플리케이션을 빌드하는 경우 Amplify Gen 2를 사용하는 것이 좋습니다.

## 에픽
<a name="authenticate-react-app-users-cognito-amplify-ui-epics"></a>

### Amazon Cognito 사용자 풀을 생성
<a name="create-an-cog-user-pool"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 사용자 풀을 생성합니다. | [Amazon Cognito 사용자 풀](https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-user-pool.html)을 생성합니다. 사용 사례에 맞게 사용자 풀의 로그인 옵션과 보안 요구 사항을 구성합니다. | 앱 개발자 | 
| 앱 클라이언트를 추가합니다. | [사용자 풀 앱 클라이언트를 구성합니다](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html). 이 클라이언트는 애플리케이션이 Amazon Cognito 사용자 풀과 상호 작용하는 데 필요합니다. | 앱 개발자 | 

### Amazon Cognito 사용자 풀을 인증자 UI 구성 요소와 통합
<a name="integrate-your-cog-user-pool-with-the-authenticator-ui-component"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| 종속 항목 설치 | `aws-amplify` 및 `@aws-amplify/ui-react` 패키지를 설치하려면 애플리케이션의 루트 디렉터리에서 다음 명령을 실행합니다.<pre>npm i @aws-amplify/ui-react aws-amplify</pre> | 앱 개발자 | 
| 사용자 풀을 구성합니다. | 다음 예에 따라 `aws-exports.js` 파일을 생성하고 `src` 폴더에 저장합니다. 이 파일은 다음 정보를 포함해야 합니다.[See the AWS documentation website for more details](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html)<pre>// replace the user pool region, id, and app client id details<br />const awsmobile = {<br />    "aws_project_region": "put_your_region_here",<br />    "aws_cognito_region": "put_your_region_here",<br />    "aws_user_pools_id": "put_your_user_pool_id_here",<br />    "aws_user_pools_web_client_id": "put_your_user_pool_app_id_here"<br />}<br /><br />export default awsmobile;</pre> | 앱 개발자 | 
| Amplify 서비스를 가져오고 구성합니다. | [See the AWS documentation website for more details](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html) | 앱 개발자 | 
| 인증자 UI 구성 요소를 추가합니다. | `Authenticator` UI 구성 요소를 표시하려면 애플리케이션의 진입점 파일(`App.js`)에 다음 코드 줄을 추가합니다.<pre>import { Authenticator } from '@aws-amplify/ui-react';<br />import '@aws-amplify/ui-react/styles.css';</pre>예시 코드 스니펫은 구성 요소의 사전 구축된 테마를 사용할 때 필요한 `Authenticator` UI 구성 요소와 Amplify UI styles.css 파일를 가져옵니다.<br />`Authenticator` UI 구성 요소는 다음과 같은 두 가지 반환 값을 제공합니다.[See the AWS documentation website for more details](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html)<br />다음 예제 구성 요소를 참조하세요.<pre>function App() {<br />    return (<br />        <Authenticator><br />            {({ signOut, user }) => (<br />                <div><br />                    <p>Welcome {user.username}</p><br />                    <button onClick={signOut}>Sign out</button><br />                </div><br />            )}<br />        </Authenticator><br />    );<br />}</pre>예시 `App.js` 파일은 이 패턴의 [추가 정보](#authenticate-react-app-users-cognito-amplify-ui-additional) 섹션을 참조하세요. | 앱 개발자 | 
| (선택 사항) 세션 정보를 검색합니다. | 사용자가 인증되면 Amplify 클라이언트에서 해당 세션에 대한 데이터를 검색할 수 있습니다. 예를 들어, 사용자 세션에서 JSON 웹 토큰(JWT)을 검색하여 해당 세션의 요청을 백엔드 API로 인증할 수 있습니다.<br />JWT가 포함된 요청 헤더의 다음 예를 참조하세요.<pre>import { fetchAuthSession } from 'aws-amplify/auth';<br />(await fetchAuthSession()).tokens?.idToken?.toString();</pre> | 앱 개발자 | 

## 문제 해결
<a name="authenticate-react-app-users-cognito-amplify-ui-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| 신규 사용자는 애플리케이션에 가입할 수 없습니다. | 다음과 같이 사용자가 사용자 풀에 등록할 수 있도록 Amazon Cognito 사용자 풀이 구성되어 있는지 확인하세요.[See the AWS documentation website for more details](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html) | 
| v5에서 v6로 업그레이드한 후 인증 구성 요소 작동이 중지되었습니다. | `Auth` 범주는 Amplify v6에서 기능적 접근 방식 및 명명된 파라미터로 이동했습니다. 이제 `aws-amplify/auth` 경로에서 직접 기능 API를 가져와야 합니다. 자세한 내용은 Amplify 설명서의 [v5에서 v6로 마이그레이션](https://docs.amplify.aws/gen1/react/build-a-backend/auth/auth-migration-guide/)을 참조하세요. | 

## 관련 리소스
<a name="authenticate-react-app-users-cognito-amplify-ui-resources"></a>
+ [Amazon Cognito 시작하기](https://aws.amazon.com/cognito/getting-started/)(AWS 웹 사이트)
+ [새로운 React 앱 생성](https://reactjs.org/docs/create-a-new-react-app.html)(React 문서)
+ [Amazon Cognito란 무엇입니까?](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) (Amazon Cognito 설명서)
+ [Amplify UI 라이브러리](https://ui.docs.amplify.aws/)(Amplify 설명서)

## 추가 정보
<a name="authenticate-react-app-users-cognito-amplify-ui-additional"></a>

`App.js` 파일에 다음 코드를 포함해야 합니다.

```
import './App.css';
import { Amplify } from 'aws-amplify';
import awsExports from './aws-exports';
import { fetchAuthSession } from 'aws-amplify/auth';
import { Authenticator } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';
Amplify.configure({ ...awsExports });
let token = (await fetchAuthSession()).tokens?.idToken?.toString();
function App() {
  return (
      <Authenticator>
        {({ signOut, user }) => (
            <div>
              <p>Welcome {user.username}</p>
                <p>Your token is: {token}</p>
              <button onClick={signOut}>Sign out</button>
            </div>
        )}
      </Authenticator>
  );
}

export default App;
```