

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

# Amazon DCV 웹 UI SDK 사용
<a name="render-ui"></a>

 다음 튜토리얼은 Amazon DCV 서버에 대해 인증하고, 연결하고, Amazon DCV 웹 UI SDK에서 `DCVViewer` React 구성 요소를 렌더링하는 방법을 보여줍니다.

**Topics**
+ [사전 조건](#prerequisites)
+ [1단계: HTML 페이지 준비](#prep-html-ui)
+ [2단계: `DCVViewer` React 구성 요소 인증, 연결 및 렌더링](#auth-conn-render)
+ [AWS-UI에서 Cloudscape Design System으로 업데이트](#updateawsuitocloudscape)

## 사전 조건
<a name="prerequisites"></a>

 `React` , `ReactDOM` , `Cloudscape Design Components React` , `Cloudscape Design Global Styles`, `Cloudscape Design Design Tokens`를 설치해야 합니다.

```
$ npm i react react-dom @cloudscape-design/components @cloudscape-design/global-styles @cloudscape-design/design-tokens
```

 `Amazon DCV Web Client SDK`도 다운로드해야 합니다. 이 작업에 대한 단계별 안내는 [Amazon DCV 웹 클라이언트 SDK 시작하기](getting-started.md) 섹션을 참조하세요.

`dcv` 모듈은 Amazon DCV 웹 UI SDK의 외부 종속성이므로, 이 모듈을 가져오기 위한 별칭을 만들어야 합니다. 예를 들어 webpack을 사용하여 웹 앱을 번들로 제공하는 경우, 다음과 같이 [resolve.alias](https://webpack.js.org/configuration/resolve/#resolvealias) 옵션을 사용할 수 있습니다.

```
const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
      dcv: path.resolve('path', 'to', 'dcv.js'),
    },
  },
};
```

번들링에 롤업을 사용하는 경우 [@rollup /plugin-alias](https://www.npmjs.com/package/@rollup/plugin-alias)를 설치하고 다음과 같이 사용할 수 있습니다.

```
import alias from '@rollup/plugin-alias';
const path = require('path');

module.exports = {
  //...
  plugins: [
    alias({
      entries: [
        { find: 'dcv', replacement: path.resolve('path', 'to', 'dcv.js') },
      ]
    })
  ]
};
```

## 1단계: HTML 페이지 준비
<a name="prep-html-ui"></a>

 웹 페이지에서 필수 JavaScript 모듈을 로드해야 하며 앱의 입력 구성 요소가 렌더링될 위치에 유효한 `id`가 있는 `<div>` HTML 요소가 있어야 합니다.

예제:

```
<!DOCTYPE html>
<html lang="en" style="height: 100%;">
  <head>
    <title>DCV first connection</title>
  </head>
  <body style="height: 100%;">
    <div id="root" style="height: 100%;"></div>
    <script type="module" src="index.js"></script>
  </body>
</html>
```

## 2단계: `DCVViewer` React 구성 요소 인증, 연결 및 렌더링
<a name="auth-conn-render"></a>

 이 섹션에서는 사용자 인증 프로세스를 완료하는 방법, Amazon DCV 서버를 연결하는 방법, `DCVViewer` React 구성 요소를 렌더링하는 방법을 보여줍니다.

 먼저 `index.js` 파일에서 `React`, `ReactDOM` 및 최상위 `App` 구성 요소를 가져옵니다.

```
import React from "react";
import ReactDOM from 'react-dom';
import App from './App';
```

앱의 최상위 컨테이너 노드를 렌더링합니다.

```
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);
```

 `App.js` 파일에서 Amazon DCV 웹 클라이언트 SDK를 ESM 모듈로 가져오고, Amazon DCV 웹 UI SDK에서 `DCVViewer` React 구성 요소와 `React` 및 `Cloudscape Design Global Styles` 패키지를 가져옵니다.

```
import React from "react";
import dcv from "dcv";
import "@cloudscape-design/global-styles/index.css";
import {DCVViewer} from "./dcv-ui/dcv-ui.js";
```

 다음은 Amazon DCV 서버에 대해 인증을 수행하고, 인증이 성공적으로 이루어진 경우 Amazon DCV 웹 UI SDK에서 `DCVViewer` React 구성 요소를 렌더링하는 방법을 보여주는 예제입니다.

```
const LOG_LEVEL = dcv.LogLevel.INFO;
const SERVER_URL = "https://your-dcv-server-url:port/";
const BASE_URL = "/static/js/dcvjs";

let auth;

function App() {
  const [authenticated, setAuthenticated] = React.useState(false);
  const [sessionId, setSessionId] = React.useState('');
  const [authToken, setAuthToken] = React.useState('');
  const [credentials, setCredentials] = React.useState({});

  const onSuccess = (_, result) => {
    var { sessionId, authToken } = { ...result[0] };

    console.log("Authentication successful.");

    setSessionId(sessionId);
    setAuthToken(authToken);
    setAuthenticated(true);
    setCredentials({});
  }

  const onPromptCredentials = (_, credentialsChallenge) => {
    let requestedCredentials = {};

    credentialsChallenge.requiredCredentials.forEach(challenge => requestedCredentials[challenge.name] = "");
    setCredentials(requestedCredentials);
  }

  const authenticate = () => {
    dcv.setLogLevel(LOG_LEVEL);

    auth = dcv.authenticate(
      SERVER_URL,
      {
        promptCredentials: onPromptCredentials,
        error: onError,
        success: onSuccess
      }
    );
  }

  const updateCredentials = (e) => {
    const { name, value } = e.target;
    setCredentials({
      ...credentials,
      [name]: value
    });
  }

  const submitCredentials = (e) => {
    auth.sendCredentials(credentials);
    e.preventDefault();
  }

  React.useEffect(() => {
    if (!authenticated) {
      authenticate();
    }
  }, [authenticated]);

  const handleDisconnect = (reason) => {
    console.log("Disconnected: " + reason.message + " (code: " + reason.code + ")");
    auth.retry();
    setAuthenticated(false);
  }

  return (
    authenticated ?
    <DCVViewer
      dcv={{
        sessionId: sessionId,
        authToken: authToken,
        serverUrl: SERVER_URL,
        baseUrl: BASE_URL,
        onDisconnect: handleDisconnect,
        logLevel: LOG_LEVEL
      }}
      uiConfig={{
        toolbar: {
          visible: true,
          fullscreenButton: true,
          multimonitorButton: true,
        },
      }}
    />
    :
    <div
      style={{
        height: window.innerHeight,
        backgroundColor: "#373737",
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <form>
        <fieldset>
          {Object.keys(credentials).map((cred) => (
            <input
              key={cred}
              name={cred}
              placeholder={cred}
              type={cred === "password" ? "password" : "text"}
              onChange={updateCredentials}
              value={credentials[cred]}
            />
          ))}
        </fieldset>
        <button
          type="submit"
          onClick={submitCredentials}
        >
          Login
        </button>
      </form>
    </div>
  );
}

const onError = (_, error) => {
  console.log("Error during the authentication: " + error.message);
}

export default App;
```

 `promptCredentials`, `error`, `success` 함수는 인증 프로세스에서 정의해야 하는 필수 콜백 함수입니다.

 Amazon DCV 서버에서 자격 증명을 요청하는 메시지가 표시되면 `promptCredentials` 콜백 함수는 Amazon DCV 서버로부터 요청된 자격 증명 챌린지를 수신합니다. Amazon DCV 서버가 시스템 인증을 사용하도록 구성된 경우 자격 증명을 사용자 이름 및 암호 형식으로 제공해야 합니다.

 인증이 실패하면 `error` 콜백 함수는 Amazon DCV 서버로부터 오류 객체를 수신합니다.

 인증에 성공하면 `success` 콜백 함수는 Amazon DCV 서버에서 사용자가 연결할 수 있는 각 세션의 세션 ID(`sessionId`) 및 권한 부여 토큰(`authToken`)이 함께 포함된 배열을 수신합니다. 위의 코드 샘플은 인증 성공 시 `DCVViewer` 구성 요소를 렌더링하도록 React 상태를 업데이트합니다.

 이 구성 요소가 허용하는 속성에 대한 자세한 내용은 [Amazon DCV 웹 UI SDK 참조](https://docs.aws.amazon.com/dcv/latest/websdkguide/dcv-viewer.html#DCVViewer)를 참조하세요.

 자체 서명된 인증서에 대한 자세한 내용은 [자체 서명된 인증서를 사용한 리디렉션 설명](https://docs.aws.amazon.com/dcv/latest/adminguide/redirection-clarifications-with-self-signed-certs.html)을 참조하세요.

## AWS-UI에서 Cloudscape Design System으로 업데이트
<a name="updateawsuitocloudscape"></a>

 SDK 버전 1.3.0부터 `DCVViewer` 구성 요소가 AWS-UI에서 발전한 [Cloudscape Design](https://cloudscape.design/)으로 업데이트되었습니다.

 Cloudscape는 AWS-UI와 다른 시각적 테마를 사용하지만 기본 코드 기반은 동일하게 유지됩니다. 따라서 `DCVViewer`를 기반으로 애플리케이션을 쉽게 마이그레이션할 수 있습니다. 마이그레이션하려면 설치한 AWS-UI 관련 NPM 패키지를 관련 Cloudscape 패키지로 교체하세요.


| AWS-UI 패키지 이름 | Cloudscape 패키지 이름 | 
| --- | --- | 
| @awsui/components-react | @cloudscape-design/components | 
| @awsui/global-styles | @cloudscape-design/global-styles | 
| @awsui/collection-hooks | @cloudscape-design/collection-hooks | 
| @awsui/design-tokens | @cloudscape-design/design-tokens | 

 마이그레이션에 대한 자세한 내용은 [AWS-UI GitHub 설명서 페이지](https://github.com/aws/awsui-documentation)를 참조하세요.