자바스크립트 빠른 시작

빠른 시작에서는 Google Workspace API를 호출하는 앱을 설정하고 실행하는 방법을 설명합니다.

Google Workspace 빠른 시작은 API 클라이언트 라이브러리를 사용하여 인증 및 승인 흐름의 일부 세부정보를 처리합니다. 자체 앱에는 클라이언트 라이브러리를 사용하는 것이 좋습니다. 이 빠른 시작에서는 테스트 환경에 적합한 간소화된 인증 방식을 사용합니다. 프로덕션 환경의 경우 앱에 적합한 액세스 사용자 인증 정보를 선택하기 전에 인증 및 승인에 대해 알아보는 것이 좋습니다.

Admin SDK API에 요청하는 자바스크립트 웹 애플리케이션을 만듭니다.

목표

  • 환경을 설정합니다.
  • 샘플을 설정합니다.
  • 샘플을 실행합니다.

기본 요건

환경 설정하기

이 빠른 시작을 완료하려면 환경을 설정하세요.

API 사용 설정

Google API를 사용하려면 먼저 Google Cloud 프로젝트에서 사용 설정해야 합니다. 단일 Google Cloud 프로젝트에서 하나 이상의 API를 사용 설정할 수 있습니다.
  • Google Cloud 콘솔에서 Admin SDK API를 사용 설정합니다.

    API 사용 설정

새 Google Cloud 프로젝트를 사용하여 이 빠른 시작을 완료하는 경우 OAuth 동의 화면을 구성하고 자신을 테스트 사용자로 추가합니다. Cloud 프로젝트에서 이 단계를 이미 완료했다면 다음 섹션으로 건너뛰세요.

  1. Google Cloud 콘솔에서 메뉴 > API 및 서비스 > OAuth 동의 화면으로 이동합니다.

    OAuth 동의 화면으로 이동

  2. 앱의 사용자 유형을 선택한 다음 만들기를 클릭합니다.
  3. 앱 등록 양식을 작성한 다음 저장하고 계속하기를 클릭합니다.
  4. 지금은 범위 추가를 건너뛰고 저장 후 계속을 클릭해도 됩니다. 앞으로 Google Workspace 조직 외부에서 사용할 앱을 만들 때는 앱에 필요한 승인 범위를 추가하고 확인해야 합니다.

  5. 사용자 유형으로 외부를 선택한 경우 테스트 사용자를 추가합니다.
    1. 테스트 사용자에서 사용자 추가를 클릭합니다.
    2. 이메일 주소 및 승인된 다른 테스트 사용자를 입력한 다음 저장하고 계속하기를 클릭합니다.
  6. 앱 등록 요약을 검토합니다. 변경하려면 수정을 클릭합니다. 앱 등록이 확인되면 대시보드로 돌아가기를 클릭합니다.

웹 애플리케이션의 사용자 인증 정보 승인

앱에서 최종 사용자를 인증하고 사용자 데이터에 액세스하려면 OAuth 2.0 클라이언트 ID를 하나 이상 만들어야 합니다. 클라이언트 ID는 Google OAuth 서버에서 단일 앱을 식별하는 데 사용됩니다. 앱이 여러 플랫폼에서 실행되는 경우 플랫폼마다 별도의 클라이언트 ID를 만들어야 합니다.
  1. Google Cloud 콘솔에서 메뉴 > API 및 서비스 > 사용자 인증 정보로 이동합니다.

    사용자 인증 정보로 이동

  2. 사용자 인증 정보 만들기 > OAuth 클라이언트 ID를 클릭합니다.
  3. 애플리케이션 유형 > 웹 애플리케이션을 클릭합니다.
  4. 이름 입력란에 사용자 인증 정보의 이름을 입력합니다. 이 이름은 Google Cloud 콘솔에만 표시됩니다.
  5. 앱과 관련된 승인된 URI를 추가합니다.
    • 클라이언트 측 앱 (자바스크립트): 승인된 자바스크립트 출처에서 URI 추가를 클릭합니다. 그런 다음 브라우저 요청에 사용할 URI를 입력합니다. 애플리케이션이 OAuth 2.0 서버로 API 요청을 보낼 수 있는 도메인을 식별합니다.
    • 서버 측 앱 (자바, Python 등): 승인된 리디렉션 URI에서 URI 추가를 클릭합니다. 그런 다음 OAuth 2.0 서버가 응답을 보낼 수 있는 엔드포인트 URI를 입력합니다.
  6. 만들기를 클릭합니다. OAuth 클라이언트 생성 완료 화면이 나타나 새 클라이언트 ID와 클라이언트 비밀번호를 표시합니다.

    클라이언트 ID를 기록해 둡니다. 클라이언트 비밀번호는 웹 애플리케이션에 사용되지 않습니다.

  7. OK(확인)를 클릭합니다. 새로 만든 사용자 인증 정보가 OAuth 2.0 클라이언트 ID 아래에 표시됩니다.

이 사용자 인증 정보는 이 빠른 시작의 후반부에서 필요하므로 기록해 둡니다.

API 키 만들기

  1. Google Cloud 콘솔에서 메뉴 > API 및 서비스 > 사용자 인증 정보로 이동합니다.

    사용자 인증 정보로 이동

  2. 사용자 인증 정보 만들기 > API 키를 클릭합니다.
  3. 새 API 키가 표시됩니다.
    • 복사 를 클릭하여 앱 코드에서 사용할 API 키를 복사합니다. API 키는 프로젝트 사용자 인증 정보의 'API 키' 섹션에서도 확인할 수 있습니다.
    • 키 제한을 클릭하여 고급 설정을 업데이트하고 API 키 사용을 제한합니다. 자세한 내용은 API 키 제한사항 적용을 참고하세요.

샘플 설정

  1. 작업 디렉터리에서 index.html라는 파일을 만듭니다.
  2. index.html 파일에 다음 샘플 코드를 붙여넣습니다.

    adminSDK/reports/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Reports API Quickstart</title>
        <meta charset="utf-8" />
      </head>
      <body>
        <p>Reports API Quickstart</p>
    
        <!--Add buttons to initiate auth sequence and sign out-->
        <button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
        <button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
    
        <pre id="content" style="white-space: pre-wrap;"></pre>
    
        <script type="text/javascript">
          /* exported gapiLoaded */
          /* exported gisLoaded */
          /* exported handleAuthClick */
          /* exported handleSignoutClick */
    
          // TODO(developer): Set to client ID and API key from the Developer Console
          const CLIENT_ID = '<YOUR_CLIENT_ID>';
          const API_KEY = '<YOUR_API_KEY>';
    
          // Discovery doc URL for APIs used by the quickstart
          const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/admin/reports_v1/rest';
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          const SCOPES = 'https://www.googleapis.com/auth/admin.reports.audit.readonly';
    
          let tokenClient;
          let gapiInited = false;
          let gisInited = false;
    
          document.getElementById('authorize_button').style.visibility = 'hidden';
          document.getElementById('signout_button').style.visibility = 'hidden';
    
          /**
           * Callback after api.js is loaded.
           */
          function gapiLoaded() {
            gapi.load('client', initializeGapiClient);
          }
    
          /**
           * Callback after the API client is loaded. Loads the
           * discovery doc to initialize the API.
           */
          async function initializeGapiClient() {
            await gapi.client.init({
              apiKey: API_KEY,
              discoveryDocs: [DISCOVERY_DOC],
            });
            gapiInited = true;
            maybeEnableButtons();
          }
    
          /**
           * Callback after Google Identity Services are loaded.
           */
          function gisLoaded() {
            tokenClient = google.accounts.oauth2.initTokenClient({
              client_id: CLIENT_ID,
              scope: SCOPES,
              callback: '', // defined later
            });
            gisInited = true;
            maybeEnableButtons();
          }
    
          /**
           * Enables user interaction after all libraries are loaded.
           */
          function maybeEnableButtons() {
            if (gapiInited && gisInited) {
              document.getElementById('authorize_button').style.visibility = 'visible';
            }
          }
    
          /**
           *  Sign in the user upon button click.
           */
          function handleAuthClick() {
            tokenClient.callback = async (resp) => {
              if (resp.error !== undefined) {
                throw (resp);
              }
              document.getElementById('signout_button').style.visibility = 'visible';
              document.getElementById('authorize_button').innerText = 'Refresh';
              await listLoginActivity();
            };
    
            if (gapi.client.getToken() === null) {
              // Prompt the user to select a Google Account and ask for consent to share their data
              // when establishing a new session.
              tokenClient.requestAccessToken({prompt: 'consent'});
            } else {
              // Skip display of account chooser and consent dialog for an existing session.
              tokenClient.requestAccessToken({prompt: ''});
            }
          }
    
          /**
           *  Sign out the user upon button click.
           */
          function handleSignoutClick() {
            const token = gapi.client.getToken();
            if (token !== null) {
              google.accounts.oauth2.revoke(token.access_token);
              gapi.client.setToken('');
              document.getElementById('content').innerText = '';
              document.getElementById('authorize_button').innerText = 'Authorize';
              document.getElementById('signout_button').style.visibility = 'hidden';
            }
          }
    
          /**
           * Print 10 recent login activities.
           */
          async function listLoginActivity() {
            let response;
            try {
              const request = {
                'userKey': 'all',
                'applicationName': 'login',
                'maxResults': 10,
              };
              response = await gapi.client.reports.activities.list(request);
            } catch (err) {
              document.getElementById('content').innerText = err.message;
              return;
            }
    
            const activities = response.result.items;
            if (!activities || activities.length == 0) {
              document.getElementById('content').innerText = 'No activities found.';
              return;
            }
            // Flatten to string to display
            const output = activities.reduce(
                (str, activity) => {
                  const time = activity.id.time;
                  const email = activity.actor.email;
                  const eventName = activity.events[0].name;
                  return `${str}-${time}: ${email} (${eventName})\n`;
                },
                'Logins:\n');
            document.getElementById('content').innerText = output;
          }
        </script>
        <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
        <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
      </body>
    </html>

    다음을 바꿉니다.

샘플 실행

  1. 작업 디렉터리에서 http-server 패키지를 설치합니다.

    npm install http-server
    
  2. 작업 디렉터리에서 웹 서버를 시작합니다.

    npx http-server -p 8000
    
  1. 브라우저에서 http://localhost:8000으로 이동합니다.
  2. 액세스를 승인하라는 메시지가 표시됩니다.
    1. 아직 Google 계정에 로그인하지 않은 경우 메시지가 표시될 때 로그인합니다. 여러 계정에 로그인되어 있는 경우 승인에 사용할 계정을 하나 선택하세요.
    2. 동의를 클릭합니다.

JavaScript 애플리케이션이 실행되고 Admin SDK API를 호출합니다.

다음 단계