웹 서버 애플리케이션용 OAuth 2.0 사용

이 문서에서는 웹 서버 애플리케이션에서 Google API 클라이언트 라이브러리 또는 Google OAuth 2.0 엔드포인트를 사용하여 Google API에 액세스하기 위한 OAuth 2.0 승인을 구현하는 방법을 설명합니다.

OAuth 2.0을 사용하면 사용자가 사용자 이름, 비밀번호, 기타 정보를 비공개로 유지하면서 특정 데이터를 애플리케이션과 공유할 수 있습니다. 예를 들어 애플리케이션에서 OAuth 2.0을 사용하여 Google 드라이브에 파일을 저장할 권한을 사용자로부터 얻을 수 있습니다.

이 OAuth 2.0 흐름은 특히 사용자 승인을 위한 절차입니다. 기밀 정보를 저장하고 상태를 유지할 수 있는 애플리케이션용으로 설계되었습니다. 올바르게 승인된 웹 서버 애플리케이션은 사용자가 애플리케이션과 상호작용하는 동안이나 사용자가 애플리케이션을 종료한 후에 API에 액세스할 수 있습니다.

웹 서버 애플리케이션은 특히 Cloud API를 호출하여 사용자별 데이터가 아닌 프로젝트 기반 데이터에 액세스할 때 서비스 계정을 사용하여 API 요청을 승인하는 경우가 많습니다. 웹 서버 애플리케이션은 사용자 승인과 함께 서비스 계정을 사용할 수 있습니다.

클라이언트 라이브러리

이 페이지의 언어별 예에서는 Google API 클라이언트 라이브러리를 사용하여 OAuth 2.0 승인을 구현합니다. 코드 샘플을 실행하려면 먼저 해당 언어의 클라이언트 라이브러리를 설치해야 합니다.

Google API 클라이언트 라이브러리를 사용하여 애플리케이션의 OAuth 2.0 흐름을 처리하는 경우, 클라이언트 라이브러리는 애플리케이션에서 자체적으로 처리해야 하는 많은 작업을 수행합니다. 예를 들어 애플리케이션이 저장된 액세스 토큰을 사용하거나 새로고침할 수 있는 시점과 애플리케이션이 동의를 다시 얻어야 하는 시점을 결정합니다. 또한 클라이언트 라이브러리는 올바른 리디렉션 URL을 생성하고 승인 코드를 액세스 토큰으로 교환하는 리디렉션 핸들러를 구현하는 데 도움이 됩니다.

서버 측 애플리케이션용 Google API 클라이언트 라이브러리는 다음 언어로 제공됩니다.

기본 요건

프로젝트에 API 사용 설정

Google API를 호출하는 모든 애플리케이션은 API Console에서 이러한 API를 사용 설정해야 합니다.

프로젝트에서 API를 사용 설정하는 방법은 다음과 같습니다.

  1. Open the API Library Google API Console.
  2. If prompted, select a project, or create a new one.
  3. API Library 에는 사용 가능한 모든 API가 제품군 및 인기도별로 그룹화되어 나열됩니다. 사용 설정하려는 API가 목록에 표시되지 않으면 검색을 사용하여 API를 찾거나 API가 속한 제품군에서 모두 보기를 클릭합니다.
  4. 사용 설정하려는 API를 선택한 다음 사용 설정 버튼을 클릭합니다.
  5. If prompted, enable billing.
  6. If prompted, read and accept the API's Terms of Service.

승인 사용자 인증 정보 만들기

OAuth 2.0을 사용하여 Google API에 액세스하는 모든 애플리케이션에는 Google의 OAuth 2.0 서버에서 애플리케이션을 식별하는 승인 사용자 인증 정보가 있어야 합니다. 다음 단계에서는 프로젝트의 사용자 인증 정보를 만드는 방법을 설명합니다. 그러면 애플리케이션에서 사용자 인증 정보를 사용하여 해당 프로젝트에 사용 설정한 API에 액세스할 수 있습니다.

  1. Go to the Credentials page.
  2. 사용자 인증 정보 만들기 > OAuth 클라이언트 ID를 클릭합니다.
  3. 웹 애플리케이션 애플리케이션 유형을 선택합니다.
  4. 양식을 작성하고 만들기를 클릭합니다. PHP, 자바, Python, Ruby, .NET과 같은 언어와 프레임워크를 사용하는 애플리케이션은 승인된 리디렉션 URI를 지정해야 합니다. 리디렉션 URI는 OAuth 2.0 서버가 응답을 보낼 수 있는 엔드포인트입니다. 이러한 엔드포인트는 Google의 유효성 검사 규칙을 준수해야 합니다.

    테스트를 위해 로컬 머신을 참조하는 URI(예: http://localhost:8080)를 지정할 수 있습니다. 이 점을 염두에 두고 이 문서의 모든 예에서는 http://localhost:8080을 리디렉션 URI로 사용합니다.

    애플리케이션이 페이지의 다른 리소스에 승인 코드를 노출하지 않도록 앱의 인증 엔드포인트를 설계하는 것이 좋습니다.

사용자 인증 정보를 만든 후 API Console에서 client_secret.json 파일을 다운로드합니다. 내 애플리케이션만 액세스할 수 있는 위치에 파일을 안전하게 저장합니다.

액세스 범위 식별

범위를 사용하면 애플리케이션이 필요한 리소스에 대한 액세스만 요청할 수 있으며 사용자는 애플리케이션에 부여하는 액세스 권한의 양을 제어할 수 있습니다. 따라서 요청된 범위의 수와 사용자 동의를 얻을 가능성 사이에 반비례 관계가 있을 수 있습니다.

OAuth 2.0 승인 구현을 시작하기 전에 앱에서 액세스 권한이 필요한 범위를 지정하는 것이 좋습니다.

또한 애플리케이션이 컨텍스트 내에서 사용자 데이터에 대한 액세스를 요청하는 증분 승인 프로세스를 통해 승인 범위에 대한 액세스를 요청하는 것이 좋습니다. 이 권장사항을 통해 사용자는 요청하는 액세스 권한이 애플리케이션에 필요한 이유를 더 쉽게 이해할 수 있습니다.

OAuth 2.0 API 범위 문서에는 Google API에 액세스하는 데 사용할 수 있는 범위의 전체 목록이 포함되어 있습니다.

언어별 요구사항

이 문서의 코드 샘플을 실행하려면 Google 계정, 인터넷 액세스 권한, 웹브라우저가 필요합니다. API 클라이언트 라이브러리 중 하나를 사용하는 경우 아래의 언어별 요구사항도 참조하세요.

2,399필리핀

이 문서의 PHP 코드 샘플을 실행하려면 다음이 필요합니다.

  • PHP 5.6 이상(명령줄 인터페이스(CLI) 및 JSON 확장 프로그램 설치)
  • Composer 종속 항목 관리 도구
  • PHP용 Google API 클라이언트 라이브러리:

    composer require google/apiclient:^2.10

Python

이 문서의 Python 코드 샘플을 실행하려면 다음이 필요합니다.

  • Python 2.6 이상
  • pip 패키지 관리 도구
  • Python용 Google API 클라이언트 라이브러리:
    pip install --upgrade google-api-python-client
  • 사용자 승인을 위한 google-auth, google-auth-oauthlib, google-auth-httplib2
    pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2
  • Flask Python 웹 애플리케이션 프레임워크입니다.
    pip install --upgrade flask
  • requests HTTP 라이브러리
    pip install --upgrade requests

Ruby

이 문서의 Ruby 코드 샘플을 실행하려면 다음이 필요합니다.

  • Ruby 2.6 이상
  • Ruby용 Google 인증 라이브러리:

    gem install googleauth
  • Sinatra Ruby 웹 애플리케이션 프레임워크입니다.

    gem install sinatra

Node.js

이 문서의 Node.js 코드 샘플을 실행하려면 다음이 필요합니다.

  • 유지보수 LTS, 활성 LTS 또는 Node.js의 현재 출시 버전입니다.
  • Google API Node.js 클라이언트:

    npm install googleapis

HTTP/REST

라이브러리를 설치하지 않아도 OAuth 2.0 엔드포인트를 직접 호출할 수 있습니다.

OAuth 2.0 액세스 토큰 가져오기

다음 단계에서는 애플리케이션이 Google의 OAuth 2.0 서버와 상호작용하여 사용자를 대신하여 API 요청을 하기 위해 사용자의 동의를 얻는 방법을 보여줍니다. 애플리케이션에서 사용자 승인이 필요한 Google API 요청을 실행하려면 먼저 이러한 동의를 얻어야 합니다.

아래 목록에는 이러한 단계가 요약되어 있습니다.

  1. 애플리케이션은 필요한 권한을 식별합니다.
  2. 애플리케이션은 요청된 권한 목록과 함께 사용자를 Google로 리디렉션합니다.
  3. 사용자가 애플리케이션에 권한을 부여할지 결정합니다.
  4. 애플리케이션이 사용자의 결정을 알아냅니다.
  5. 사용자가 요청된 권한을 부여하면 애플리케이션이 사용자를 대신하여 API 요청을 하는 데 필요한 토큰을 검색합니다.

1단계: 승인 매개변수 설정

첫 번째 단계는 승인 요청을 생성하는 것입니다. 이 요청은 애플리케이션을 식별하는 매개변수를 설정하고 사용자가 애플리케이션에 부여할 권한을 정의합니다.

  • OAuth 2.0 인증 및 승인에 Google 클라이언트 라이브러리를 사용하는 경우 이러한 매개변수를 정의하는 객체를 만들고 구성합니다.
  • Google OAuth 2.0 엔드포인트를 직접 호출하는 경우 URL을 생성하고 해당 URL에 매개변수를 설정합니다.

아래 탭에서는 웹 서버 애플리케이션에 지원되는 승인 매개변수를 정의합니다. 언어별 예시에서는 클라이언트 라이브러리 또는 승인 라이브러리를 사용하여 이러한 매개변수를 설정하는 객체를 구성하는 방법도 보여줍니다.

2,399필리핀

아래의 코드 스니펫은 승인 요청의 매개변수를 정의하는 Google\Client() 객체를 만듭니다.

이 객체는 client_secret.json 파일의 정보를 사용하여 애플리케이션을 식별합니다. 해당 파일에 대한 자세한 내용은 승인 사용자 인증 정보 만들기를 참조하세요. 또한 이 객체는 애플리케이션이 액세스 권한을 요청하는 범위와 Google OAuth 2.0 서버의 응답을 처리하는 애플리케이션의 인증 엔드포인트 URL을 식별합니다. 마지막으로 코드는 선택적 access_typeinclude_granted_scopes 매개변수를 설정합니다.

예를 들어 다음 코드는 사용자의 Google Drive에 대한 읽기 전용 오프라인 액세스를 요청합니다.

$client = new Google\Client();

// Required, call the setAuthConfig function to load authorization credentials from
// client_secret.json file.
$client->setAuthConfig('client_secret.json');

// Required, to set the scope value, call the addScope function
$client->addScope(Google\Service\Drive::DRIVE_METADATA_READONLY);

// Required, call the setRedirectUri function to specify a valid redirect URI for the
// provided client_id
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');

// Recommended, offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');

// Recommended, call the setState function. Using a state value can increase your assurance that
// an incoming connection is the result of an authentication request.
$client->setState($sample_passthrough_value);

// Optional, if your application knows which user is trying to authenticate, it can use this
// parameter to provide a hint to the Google Authentication Server.
$client->setLoginHint('hint@example.com');

// Optional, call the setPrompt function to set "consent" will prompt the user for consent
$client->setPrompt('consent');

// Optional, call the setIncludeGrantedScopes function with true to enable incremental
// authorization
$client->setIncludeGrantedScopes(true);

Python

다음 코드 스니펫은 google-auth-oauthlib.flow 모듈을 사용하여 승인 요청을 구성합니다.

이 코드는 승인 사용자 인증 정보를 생성한 후 다운로드한 client_secret.json 파일의 정보를 사용하여 애플리케이션을 식별하는 Flow 객체를 구성합니다. 또한 이 객체는 애플리케이션이 액세스 권한을 요청하는 범위와 Google OAuth 2.0 서버의 응답을 처리하는 애플리케이션의 인증 엔드포인트 URL을 식별합니다. 마지막으로 코드는 선택적 access_typeinclude_granted_scopes 매개변수를 설정합니다.

예를 들어 다음 코드는 사용자의 Google Drive에 대한 읽기 전용 오프라인 액세스를 요청합니다.

import google.oauth2.credentials
import google_auth_oauthlib.flow

# Required, call the from_client_secrets_file method to retrieve the client ID from a
# client_secret.json file. The client ID (from that file) and access scopes are required. (You can
# also use the from_client_config method, which passes the client configuration as it originally
# appeared in a client secrets file but doesn't access the file itself.)
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    'client_secret.json',
    scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'])

# Required, indicate where the API server will redirect the user after the user completes
# the authorization flow. The redirect URI is required. The value must exactly
# match one of the authorized redirect URIs for the OAuth 2.0 client, which you
# configured in the API Console. If this value doesn't match an authorized URI,
# you will get a 'redirect_uri_mismatch' error.
flow.redirect_uri = 'https://www.example.com/oauth2callback'

# Generate URL for request to Google's OAuth 2.0 server.
# Use kwargs to set optional request parameters.
authorization_url, state = flow.authorization_url(
    # Recommended, enable offline access so that you can refresh an access token without
    # re-prompting the user for permission. Recommended for web server apps.
    access_type='offline',
    # Optional, enable incremental authorization. Recommended as a best practice.
    include_granted_scopes='true',
    # Recommended, state value can increase your assurance that an incoming connection is the result
    # of an authentication request.
    state=sample_passthrough_value,
    # Optional, if your application knows which user is trying to authenticate, it can use this
    # parameter to provide a hint to the Google Authentication Server.
    login_hint='hint@example.com',
    # Optional, set prompt to 'consent' will prompt the user for consent
    prompt='consent')

Ruby

만든 client_secrets.json 파일을 사용하여 애플리케이션에서 클라이언트 객체를 구성합니다. 클라이언트 객체를 구성할 때 OAuth 2.0 서버의 응답을 처리할 애플리케이션의 인증 엔드포인트 URL과 함께 애플리케이션에서 액세스해야 하는 범위를 지정합니다.

예를 들어 다음 코드는 사용자의 Google Drive에 대한 읽기 전용 오프라인 액세스를 요청합니다.

require 'google/apis/drive_v3'
require "googleauth"
require 'googleauth/stores/redis_token_store'

client_id = Google::Auth::ClientId.from_file('/path/to/client_secret.json')
scope = 'https://www.googleapis.com/auth/drive.metadata.readonly'
token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)
authorizer = Google::Auth::WebUserAuthorizer.new(client_id, scope, token_store, '/oauth2callback')

애플리케이션에서는 클라이언트 객체를 사용하여 승인 요청 URL을 생성하고 HTTP 요청에 액세스 토큰을 적용하는 등의 OAuth 2.0 작업을 수행합니다.

Node.js

아래의 코드 스니펫은 승인 요청의 매개변수를 정의하는 google.auth.OAuth2 객체를 만듭니다.

이 객체는 client_secret.json 파일의 정보를 사용하여 애플리케이션을 식별합니다. 사용자에게 액세스 토큰을 가져올 권한을 요청하려면 동의 페이지로 리디렉션합니다. 동의 페이지 URL을 만들려면 다음 단계를 따르세요.

const {google} = require('googleapis');

/**
 * To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI
 * from the client_secret.json file. To get these credentials for your application, visit
 * https://console.cloud.google.com/apis/credentials.
 */
const oauth2Client = new google.auth.OAuth2(
  YOUR_CLIENT_ID,
  YOUR_CLIENT_SECRET,
  YOUR_REDIRECT_URL
);

// Access scopes for read-only Drive activity.
const scopes = [
  'https://www.googleapis.com/auth/drive.metadata.readonly'
];

// Generate a url that asks permissions for the Drive activity scope
const authorizationUrl = oauth2Client.generateAuthUrl({
  // 'online' (default) or 'offline' (gets refresh_token)
  access_type: 'offline',
  /** Pass in the scopes array defined above.
    * Alternatively, if only one scope is needed, you can pass a scope URL as a string */
  scope: scopes,
  // Enable incremental authorization. Recommended as a best practice.
  include_granted_scopes: true
});

중요 사항 - refresh_token는 첫 번째 승인 시에만 반환됩니다. 자세한 내용은 여기를 참조하세요.

HTTP/REST

Google의 OAuth 2.0 엔드포인트는 https://accounts.google.com/o/oauth2/v2/auth에 있습니다. 이 엔드포인트는 HTTPS를 통해서만 액세스할 수 있습니다. 일반 HTTP 연결은 거부됩니다.

Google 승인 서버는 웹 서버 애플리케이션에 대해 다음과 같은 쿼리 문자열 매개변수를 지원합니다.

매개변수
client_id 필수 항목

애플리케이션의 클라이언트 ID입니다. 이 값은 API Console Credentials page에서 찾을 수 있습니다.

redirect_uri 필수 항목

사용자가 승인 흐름을 완료한 후 API 서버가 사용자를 리디렉션하는 위치를 결정합니다. 이 값은 클라이언트의 API Console Credentials page에서 구성한 OAuth 2.0 클라이언트의 승인된 리디렉션 URI 중 하나와 정확히 일치해야 합니다. 이 값이 제공된 client_id의 승인된 리디렉션 URI와 일치하지 않으면 redirect_uri_mismatch 오류가 발생합니다.

http 또는 https 스키마, 대소문자, 후행 슬래시('/')가 모두 일치해야 합니다.

response_type 필수 항목

Google OAuth 2.0 엔드포인트에서 승인 코드를 반환하는지 여부를 결정합니다.

웹 서버 애플리케이션의 경우 매개변수 값을 code로 설정합니다.

scope 필수 항목

사용자를 대신하여 애플리케이션에서 액세스할 수 있는 리소스를 식별하는 공백으로 구분된 범위 목록입니다. 이 값은 Google에서 사용자에게 표시하는 동의 화면을 나타냅니다.

범위를 사용하면 애플리케이션이 필요한 리소스에 대한 액세스만 요청할 수 있으며 사용자는 애플리케이션에 부여하는 액세스 권한의 양을 제어할 수 있습니다. 따라서 요청된 범위의 수와 사용자 동의를 얻을 가능성 사이에는 반비례 관계가 있습니다.

가능한 경우 애플리케이션에서 컨텍스트 내에서 승인 범위에 대한 액세스를 요청하는 것이 좋습니다. 증분 승인을 통해 컨텍스트 내에서 사용자 데이터에 대한 액세스를 요청하면 애플리케이션에서 요청하는 액세스가 필요한 이유를 사용자가 더 쉽게 이해할 수 있습니다.

access_type 권장됨

사용자가 브라우저에 없을 때 애플리케이션이 액세스 토큰을 새로고침할 수 있는지 여부를 나타냅니다. 유효한 매개변수 값은 기본값인 onlineoffline입니다.

사용자가 브라우저에 없을 때 애플리케이션이 액세스 토큰을 새로고침해야 하면 값을 offline로 설정합니다. 이 문서의 뒷부분에서 설명하는 액세스 토큰을 갱신하는 방법입니다. 이 값은 애플리케이션에서 처음으로 승인 코드를 토큰으로 교환할 때 갱신 토큰 액세스 토큰을 반환하도록 Google 승인 서버에 지시합니다.

state 권장됨

애플리케이션이 승인 요청과 승인 서버 응답 사이의 상태를 유지하는 데 사용하는 문자열 값을 지정합니다. 사용자가 애플리케이션의 액세스 요청에 동의하거나 거부한 후 서버는 redirect_uri의 URL 쿼리 구성요소 (?)에서 name=value 쌍으로 전송하는 정확한 값을 반환합니다.

사용자를 애플리케이션의 올바른 리소스로 안내하거나 nonce를 전송하고 교차 사이트 요청 위조 완화를 비롯한 여러 용도로 이 매개변수를 사용할 수 있습니다. redirect_uri는 추측할 수 있으므로 state 값을 사용하면 수신 연결이 인증 요청의 결과임을 확신할 수 있습니다. 임의의 문자열을 생성하거나 클라이언트 상태를 캡처하는 쿠키 또는 다른 값의 해시를 인코딩하는 경우 응답의 유효성을 검사하여 요청과 응답이 동일한 브라우저에서 시작되었는지 추가로 확인할 수 있습니다. 이를 통해 교차 사이트 요청 위조와 같은 공격으로부터 보호할 수 있습니다. state 토큰을 만들고 확인하는 방법의 예시는 OpenID Connect 문서를 참조하세요.

include_granted_scopes Optional

애플리케이션에서 증분 승인을 사용하여 컨텍스트 내에서 추가 범위에 대한 액세스를 요청할 수 있습니다. 이 매개변수의 값을 true로 설정하고 승인 요청이 승인되면 사용자가 이전에 애플리케이션 액세스 권한을 부여한 모든 범위에도 새 액세스 토큰이 적용됩니다. 예시는 증분 승인 섹션을 참조하세요.

login_hint Optional

애플리케이션이 인증을 시도하는 사용자를 알고 있으면 이 매개변수를 사용하여 Google 인증 서버에 힌트를 제공할 수 있습니다. 서버는 힌트를 사용하여 로그인 양식의 이메일 필드를 미리 채우거나 적절한 멀티 로그인 세션을 선택하여 로그인 흐름을 간소화합니다.

매개변수 값을 사용자의 Google ID에 해당하는 이메일 주소 또는 sub 식별자로 설정합니다.

prompt Optional

공백으로 구분된 대소문자 구분 프롬프트 목록으로, 사용자에게 표시됩니다. 이 매개변수를 지정하지 않으면 프로젝트에서 처음 액세스를 요청할 때만 사용자에게 메시지가 표시됩니다. 자세한 내용은 재동의 메시지 표시를 참고하세요.

가능한 값은 다음과 같습니다.

none 인증 또는 동의 화면을 표시하지 않습니다. 다른 값으로 지정해서는 안 됩니다.
consent 사용자에게 동의를 요청하는 메시지를 표시합니다.
select_account 사용자에게 계정을 선택하라는 메시지를 표시합니다.

2단계: Google의 OAuth 2.0 서버로 리디렉션하기

사용자를 Google의 OAuth 2.0 서버로 리디렉션하여 인증 및 승인 프로세스를 시작합니다. 일반적으로 애플리케이션이 사용자의 데이터에 처음 액세스해야 할 때 이러한 상황이 발생합니다. 증분 승인의 경우 애플리케이션이 아직 액세스 권한이 없는 추가 리소스에 처음 액세스해야 하는 경우에도 이 단계가 발생합니다.

2,399필리핀

  1. Google OAuth 2.0 서버에서 액세스를 요청하는 URL을 생성합니다.
    $auth_url = $client->createAuthUrl();
  2. 사용자를 $auth_url로 리디렉션합니다.
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));

Python

이 예시에서는 Flask 웹 애플리케이션 프레임워크를 사용하여 사용자를 승인 URL로 리디렉션하는 방법을 보여줍니다.

return flask.redirect(authorization_url)

Ruby

  1. Google OAuth 2.0 서버에서 액세스를 요청하는 URL을 생성합니다.
    auth_uri = authorizer.get_authorization_url(login_hint: user_id, request: request)
  2. 사용자를 auth_uri로 리디렉션합니다.

Node.js

  1. 1단계 generateAuthUrl 메서드에서 생성된 URL authorizationUrl를 사용하여 Google의 OAuth 2.0 서버에서 액세스를 요청합니다.
  2. 사용자를 authorizationUrl로 리디렉션합니다.
    res.writeHead(301, { "Location": authorizationUrl });

HTTP/REST

Sample redirect to Google's authorization server

An example URL is shown below, with line breaks and spaces for readability.

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly&
 access_type=offline&
 include_granted_scopes=true&
 response_type=code&
 state=state_parameter_passthrough_value&
 redirect_uri=https%3A//oauth2.example.com/code&
 client_id=client_id

요청 URL을 만든 후 사용자를 이 URL로 리디렉션합니다.

Google의 OAuth 2.0 서버는 사용자를 인증하고 애플리케이션이 요청된 범위에 액세스하는 것에 대해 사용자의 동의를 얻습니다. 지정된 리디렉션 URL을 사용하여 응답이 애플리케이션으로 다시 전송됩니다.

3단계: Google에서 사용자에게 동의 요청 메시지 표시

이 단계에서 사용자는 애플리케이션에 요청된 액세스 권한을 부여할지 여부를 결정합니다. 이 단계에서 Google은 애플리케이션의 이름과 사용자의 승인 사용자 인증 정보로 액세스 권한을 요청하는 Google API 서비스의 이름과 부여할 액세스 범위의 요약을 표시합니다. 그러면 사용자는 애플리케이션에서 요청한 하나 이상의 범위에 대한 액세스 권한을 부여하는 데 동의하거나 요청을 거부할 수 있습니다.

액세스 권한이 부여되었는지 여부를 나타내는 Google OAuth 2.0 서버의 응답을 기다리므로 애플리케이션은 이 단계에서 어떤 작업도 수행할 필요가 없습니다. 이 응답은 다음 단계에서 설명합니다.

오류

Google의 OAuth 2.0 승인 엔드포인트에 요청하면 예상되는 인증 및 승인 흐름 대신 사용자에게 표시되는 오류 메시지가 표시될 수 있습니다. 일반적인 오류 코드와 추천 해결 방법은 아래와 같습니다.

admin_policy_enforced

Google Workspace 관리자의 정책으로 인해 Google 계정에서 요청된 범위 중 하나 이상을 승인할 수 없습니다. OAuth 클라이언트 ID에 액세스 권한이 명시적으로 부여될 때까지 관리자가 모든 범위 또는 민감한 범위 및 제한된 범위에 대한 액세스를 제한하는 방법에 대한 자세한 내용은 Google Workspace 관리자 도움말 문서 Google Workspace 데이터에 액세스할 수 있는 서드 파티 및 내부 앱 제어를 참조하세요.

disallowed_useragent

승인 엔드포인트가 Google의 OAuth 2.0 정책에서 허용하지 않는 삽입된 사용자 에이전트 내에 표시됩니다.

Android

Android 개발자가 android.webkit.WebView에서 승인 요청을 열 때 이 오류 메시지가 표시될 수 있습니다. 개발자는 대신 Android용 Google 로그인 또는 OpenID Foundation의 Android용 AppAuth와 같은 Android 라이브러리를 사용해야 합니다.

웹 개발자는 Android 앱이 삽입된 사용자 에이전트에서 일반 웹 링크를 열고 사용자가 사이트에서 Google의 OAuth 2.0 승인 엔드포인트로 이동할 때 이 오류가 발생할 수 있습니다. 개발자는 Android App Links 핸들러 또는 기본 브라우저 앱이 모두 포함된 운영체제의 기본 링크 핸들러에서 일반 링크를 열 수 있도록 허용해야 합니다. Android 맞춤 탭 라이브러리도 지원되는 옵션입니다.

iOS

iOS 및 macOS 개발자는 WKWebView에서 승인 요청을 열 때 이 오류가 발생할 수 있습니다. 개발자는 대신 iOS용 Google 로그인 또는 OpenID Foundation의 iOS용 AppAuth와 같은 iOS 라이브러리를 사용해야 합니다.

웹 개발자는 iOS 또는 macOS 앱이 삽입된 사용자 에이전트에서 일반 웹 링크를 열고 사용자가 사이트에서 Google의 OAuth 2.0 승인 엔드포인트로 이동할 때 이 오류가 발생할 수 있습니다. 개발자는 범용 링크 핸들러 또는 기본 브라우저 앱이 모두 포함된 운영체제의 기본 링크 핸들러에서 일반 링크를 열 수 있도록 허용해야 합니다. SFSafariViewController 라이브러리도 지원되는 옵션입니다.

org_internal

요청의 OAuth 클라이언트 ID는 특정 Google Cloud 조직의 Google 계정에 대한 액세스를 제한하는 프로젝트의 일부입니다. 이 구성 옵션에 관한 자세한 내용은 OAuth 동의 화면 설정 도움말 문서의 사용자 유형 섹션을 참고하세요.

invalid_client

OAuth 클라이언트 보안 비밀번호가 잘못되었습니다. 이 요청에 사용된 클라이언트 ID와 보안 비밀을 포함하여 OAuth 클라이언트 구성을 검토합니다.

invalid_grant

액세스 토큰을 새로고침하거나 증분 승인을 사용하는 경우 토큰이 만료되었거나 무효화되었을 수 있습니다. 사용자를 다시 인증하고 새 토큰을 얻기 위해 사용자 동의를 요청합니다. 이 오류가 계속 표시되면 애플리케이션이 올바르게 구성되었는지, 요청에 올바른 토큰과 매개변수를 사용하고 있는지 확인하세요. 그 외의 경우에는 사용자 계정이 삭제되었거나 사용 중지되었을 수 있습니다.

redirect_uri_mismatch

승인 요청에서 전달된 redirect_uri가 OAuth 클라이언트 ID의 승인된 리디렉션 URI와 일치하지 않습니다. Google API Console Credentials page에서 승인된 리디렉션 URI를 검토합니다.

redirect_uri 매개변수는 지원 중단되어 더 이상 지원되지 않는 OAuth 대역 외 (OOB) 흐름을 참조할 수 있습니다. 통합을 업데이트하려면 이전 가이드를 참고하세요.

invalid_request

요청에 문제가 발생했습니다. 다음과 같은 여러 가지 이유가 있을 수 있습니다.

  • 요청의 형식이 잘못되었습니다.
  • 요청에 필수 매개변수가 누락되었습니다.
  • 요청에 Google에서 지원하지 않는 승인 방법이 사용되었습니다. OAuth 통합에서 권장되는 통합 방법을 사용하는지 확인

4단계: OAuth 2.0 서버 응답 처리

OAuth 2.0 서버는 요청에 지정된 URL을 사용하여 애플리케이션의 액세스 요청에 응답합니다.

사용자가 액세스 요청을 승인하면 응답에 승인 코드가 포함됩니다. 사용자가 요청을 승인하지 않으면 응답에 오류 메시지가 포함됩니다. 웹 서버에 반환되는 승인 코드 또는 오류 메시지는 아래와 같이 쿼리 문자열에 표시됩니다.

오류 응답:

https://oauth2.example.com/auth?error=access_denied

승인 코드 응답:

https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7

OAuth 2.0 서버 응답 샘플

Google Drive에 있는 파일의 메타데이터를 볼 수 있는 읽기 전용 액세스 권한을 요청하는 다음 샘플 URL을 클릭하여 이 흐름을 테스트할 수 있습니다.

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly&
 access_type=offline&
 include_granted_scopes=true&
 response_type=code&
 state=state_parameter_passthrough_value&
 redirect_uri=https%3A//oauth2.example.com/code&
 client_id=client_id

OAuth 2.0 흐름이 완료되면 http://localhost/oauth2callback로 리디렉션되어야 합니다. 로컬 머신에서 해당 주소에서 파일을 제공하지 않으면 404 NOT FOUND 오류가 발생할 수 있습니다. 다음 단계에서는 사용자가 애플리케이션으로 다시 리디렉션될 때 URI에 반환되는 정보에 관해 자세히 설명합니다.

5단계: 승인 코드를 갱신 토큰 및 액세스 토큰으로 교환

웹 서버는 승인 코드를 받은 후 승인 코드를 액세스 토큰으로 교환할 수 있습니다.

2,399필리핀

승인 코드를 액세스 토큰으로 교환하려면 authenticate 메서드를 사용합니다.

$client->authenticate($_GET['code']);

getAccessToken 메서드로 액세스 토큰을 가져올 수 있습니다.

$access_token = $client->getAccessToken();

Python

콜백 페이지에서 google-auth 라이브러리를 사용하여 승인 서버 응답을 확인합니다. 그런 다음 flow.fetch_token 메서드를 사용하여 응답의 승인 코드를 액세스 토큰으로 교환합니다.

state = flask.session['state']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
    'client_secret.json',
    scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'],
    state=state)
flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)

# Store the credentials in the session.
# ACTION ITEM for developers:
#     Store user's access and refresh tokens in your data store if
#     incorporating this code into your real app.
credentials = flow.credentials
flask.session['credentials'] = {
    'token': credentials.token,
    'refresh_token': credentials.refresh_token,
    'token_uri': credentials.token_uri,
    'client_id': credentials.client_id,
    'client_secret': credentials.client_secret,
    'scopes': credentials.scopes}

Ruby

콜백 페이지에서 googleauth 라이브러리를 사용하여 승인 서버 응답을 확인합니다. authorizer.handle_auth_callback_deferred 메서드를 사용하여 승인 코드를 저장하고 원래 승인을 요청한 URL로 다시 리디렉션합니다. 이렇게 하면 사용자 세션에 결과를 일시적으로 저장하여 코드 교환이 지연됩니다.

  target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
  redirect target_url

Node.js

승인 코드를 액세스 토큰으로 교환하려면 getToken 메서드를 사용합니다.

const url = require('url');

// Receive the callback from Google's OAuth 2.0 server.
if (req.url.startsWith('/oauth2callback')) {
  // Handle the OAuth 2.0 server response
  let q = url.parse(req.url, true).query;

  // Get access and refresh tokens (if access_type is offline)
  let { tokens } = await oauth2Client.getToken(q.code);
  oauth2Client.setCredentials(tokens);
}

HTTP/REST

승인 코드를 액세스 토큰으로 교환하려면 https://oauth2.googleapis.com/token 엔드포인트를 호출하고 다음 매개변수를 설정합니다.

입력란
client_id Credentials page에서 가져온 API Console 클라이언트 ID
client_secret Credentials page에서 가져온 API Console클라이언트 보안 비밀번호입니다.
code 초기 요청에서 반환된 승인 코드입니다.
grant_type OAuth 2.0 사양에 정의된 대로 이 필드의 값은 authorization_code로 설정해야 합니다.
redirect_uri 지정된 client_id의 API Console Credentials page 에 프로젝트의 리디렉션 URI 중 하나입니다.

다음 스니펫은 샘플 요청을 보여줍니다.

POST /token HTTP/1.1
Host: oauth2.googleapis.com
Content-Type: application/x-www-form-urlencoded

code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=https%3A//oauth2.example.com/code&
grant_type=authorization_code

Google은 수명이 짧은 액세스 토큰과 갱신 토큰이 포함된 JSON 객체를 반환하여 이 요청에 응답합니다. 갱신 토큰은 애플리케이션이 Google 승인 서버에 대한 초기 요청에서 access_type 매개변수를 offline로 설정한 경우에만 반환됩니다.

응답에는 다음 필드가 포함됩니다.

입력란
access_token 애플리케이션에서 Google API 요청을 승인하기 위해 보내는 토큰입니다.
expires_in 액세스 토큰의 남은 수명(초)입니다.
refresh_token 새 액세스 토큰을 얻는 데 사용할 수 있는 토큰입니다. 갱신 토큰은 사용자가 액세스 권한을 취소할 때까지 유효합니다. 이 필드는 Google 승인 서버에 대한 초기 요청에서 access_type 매개변수를 offline로 설정한 경우에만 이 응답에 표시됩니다.
scope access_token에 의해 부여된 액세스 범위이며 공백으로 구분되고 대소문자를 구분하는 문자열 목록으로 표시됩니다.
token_type 반환된 토큰의 유형입니다. 현재 이 필드의 값은 항상 Bearer로 설정됩니다.

다음 스니펫은 샘플 응답을 보여줍니다.

{
  "access_token": "1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in": 3920,
  "token_type": "Bearer",
  "scope": "https://www.googleapis.com/auth/drive.metadata.readonly",
  "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

오류

승인 코드를 액세스 토큰과 교환할 때 예상 응답 대신 다음 오류가 발생할 수 있습니다. 일반적인 오류 코드와 추천 해결 방법은 아래와 같습니다.

invalid_grant

제공된 승인 코드가 잘못되었거나 형식이 잘못되었습니다. 사용자에게 동의를 다시 요청하는 메시지를 표시하려면 OAuth 프로세스를 다시 시작하여 새 코드를 요청합니다.

Google API 호출

2,399필리핀

다음 단계에 따라 액세스 토큰을 사용하여 Google API를 호출합니다.

  1. Google\Client 객체에 액세스 토큰을 적용해야 하는 경우(예: 사용자 세션에 액세스 토큰을 저장한 경우) setAccessToken 메서드를 사용합니다.
    $client->setAccessToken($access_token);
  2. 호출하려는 API의 서비스 객체를 빌드합니다. 호출하려는 API의 생성자에 승인된 Google\Client 객체를 제공하여 서비스 객체를 빌드합니다. 예를 들어 Drive API를 호출하려면 다음 안내를 따르세요.
    $drive = new Google\Service\Drive($client);
  3. 서비스 객체에서 제공하는 인터페이스를 사용하여 API 서비스에 요청합니다. 예를 들어 인증된 사용자의 Google Drive에 있는 파일을 나열하려면 다음 안내를 따르세요.
    $files = $drive->files->listFiles(array())->getItems();

Python

액세스 토큰을 얻으면 애플리케이션은 해당 토큰을 사용하여 지정된 사용자 계정 또는 서비스 계정 대신에 API 요청을 승인할 수 있습니다. 사용자별 승인 사용자 인증 정보를 사용하여 호출할 API의 서비스 객체를 빌드하고 이 객체를 사용하여 승인된 API 요청을 만듭니다.

  1. 호출하려는 API의 서비스 객체를 빌드합니다. API의 이름 및 버전과 사용자 인증 정보를 사용하여 googleapiclient.discovery 라이브러리의 build 메서드를 호출하여 서비스 객체를 빌드합니다. 예를 들어 Drive API 버전 3을 호출하는 방법은 다음과 같습니다.
    from googleapiclient.discovery import build
    
    drive = build('drive', 'v2', credentials=credentials)
  2. 서비스 객체에서 제공하는 인터페이스를 사용하여 API 서비스에 요청합니다. 예를 들어 인증된 사용자의 Google Drive에 있는 파일을 나열하려면 다음 안내를 따르세요.
    files = drive.files().list().execute()

Ruby

액세스 토큰을 얻으면 애플리케이션은 이 토큰을 사용하여 지정된 사용자 계정이나 서비스 계정 대신에 API 요청을 할 수 있습니다. 사용자별 승인 사용자 인증 정보를 사용하여 호출할 API의 서비스 객체를 빌드하고 이 객체를 사용하여 승인된 API 요청을 만듭니다.

  1. 호출하려는 API의 서비스 객체를 빌드합니다. 예를 들어 Drive API 버전 3을 호출하려면 다음 안내를 따르세요.
    drive = Google::Apis::DriveV3::DriveService.new
  2. 서비스의 사용자 인증 정보를 설정합니다.
    drive.authorization = credentials
  3. 서비스 객체에서 제공하는 인터페이스를 사용하여 API 서비스에 요청합니다. 예를 들어 인증된 사용자의 Google Drive에 있는 파일을 나열하려면 다음을 실행합니다.
    files = drive.list_files

또는 options 매개변수를 메서드에 제공하여 메서드별로 승인을 제공할 수 있습니다.

files = drive.list_files(options: { authorization: credentials })

Node.js

액세스 토큰을 가져와서 OAuth2 객체로 설정한 후 이 객체를 사용하여 Google API를 호출합니다. 애플리케이션은 이 토큰을 사용하여 지정된 사용자 계정 또는 서비스 계정 대신 API 요청을 승인할 수 있습니다. 호출하려는 API의 서비스 객체를 빌드합니다.

const { google } = require('googleapis');

// Example of using Google Drive API to list filenames in user's Drive.
const drive = google.drive('v3');
drive.files.list({
  auth: oauth2Client,
  pageSize: 10,
  fields: 'nextPageToken, files(id, name)',
}, (err1, res1) => {
  if (err1) return console.log('The API returned an error: ' + err1);
  const files = res1.data.files;
  if (files.length) {
    console.log('Files:');
    files.map((file) => {
      console.log(`${file.name} (${file.id})`);
    });
  } else {
    console.log('No files found.');
  }
});

HTTP/REST

애플리케이션이 액세스 토큰을 얻은 후 API에 필요한 액세스 범위가 부여된 경우 토큰을 사용하여 지정된 사용자 계정을 대신하여 Google API를 호출할 수 있습니다. 이렇게 하려면 access_token 쿼리 매개변수 또는 Authorization HTTP 헤더 Bearer 값을 포함하여 API에 대한 요청에 액세스 토큰을 포함합니다. 쿼리 문자열은 서버 로그에 표시되는 경향이 있으므로 가능하면 HTTP 헤더를 사용하는 것이 좋습니다. 대부분의 경우 클라이언트 라이브러리를 사용하여 Google API 호출을 설정할 수 있습니다 (예: Drive Files API를 호출할 때).

OAuth 2.0 플레이그라운드에서 모든 Google API를 사용해 보고 범위를 확인할 수 있습니다.

HTTP GET 예시

Authorization: Bearer HTTP 헤더를 사용한 drive.files 엔드포인트 (Drive Files API) 호출은 다음과 같습니다. 자체 액세스 토큰을 지정해야 합니다.

GET /drive/v2/files HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer access_token

다음은 access_token 쿼리 문자열 매개변수를 사용하여 인증된 사용자를 대상으로 동일한 API를 호출하는 방법입니다.

GET https://www.googleapis.com/drive/v2/files?access_token=access_token

curl

curl 명령줄 애플리케이션을 사용하여 이러한 명령어를 테스트할 수 있습니다. 다음은 HTTP 헤더 옵션 (권장)을 사용하는 예입니다.

curl -H "Authorization: Bearer access_token" https://www.googleapis.com/drive/v2/files

또는 다음 쿼리 문자열 매개변수 옵션을 사용할 수 있습니다.

curl https://www.googleapis.com/drive/v2/files?access_token=access_token

전체 예

다음 예에서는 사용자가 인증하고 애플리케이션이 사용자의 드라이브 메타데이터에 액세스하는 데 동의한 후 사용자의 Google 드라이브에 있는 JSON 형식의 파일 목록을 출력합니다.

2,399필리핀

이 예시를 실행하려면 다음 안내를 따르세요.

  1. API Console에서 로컬 머신의 URL을 리디렉션 URL 목록에 추가합니다. 예를 들어 http://localhost:8080를 추가합니다.
  2. 새 디렉터리를 만들어 해당 디렉터리로 변경합니다. 예를 들면 다음과 같습니다.
    mkdir ~/php-oauth2-example
    cd ~/php-oauth2-example
  3. Composer를 사용하여 PHP용 Google API 클라이언트 라이브러리를 설치합니다.
    composer require google/apiclient:^2.10
  4. 아래 콘텐츠로 index.phpoauth2callback.php 파일을 만듭니다.
  5. PHP를 제공하도록 구성된 웹 서버를 사용하여 예를 실행합니다. PHP 5.6 이상을 사용하는 경우 PHP의 내장 테스트 웹 서버를 사용할 수 있습니다.
    php -S localhost:8080 ~/php-oauth2-example

index.php

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google\Client();
$client->setAuthConfig('client_secrets.json');
$client->addScope(Google\Service\Drive::DRIVE_METADATA_READONLY);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
  $drive = new Google\Service\Drive($client);
  $files = $drive->files->listFiles(array())->getItems();
  echo json_encode($files);
} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

oauth2callback.php

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google\Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google\Service\Drive::DRIVE_METADATA_READONLY);

if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

Python

이 예에서는 Flask 프레임워크를 사용합니다. OAuth 2.0 흐름을 테스트할 수 있는 웹 애플리케이션을 http://localhost:8080에서 실행합니다. 이 URL로 이동하면 링크 4개가 표시됩니다.

  • API 요청 테스트: 이 링크는 샘플 API 요청을 실행하려는 페이지를 가리킵니다. 필요한 경우 승인 흐름이 시작됩니다. 성공하면 페이지에 API 응답이 표시됩니다.
  • 인증 흐름 직접 테스트: 이 링크는 승인 흐름을 통해 사용자를 보내려고 시도하는 페이지로 연결됩니다. 앱이 사용자를 대신하여 승인된 API 요청을 제출할 권한을 요청합니다.
  • 현재 사용자 인증 정보 취소: 이 링크는 사용자가 애플리케이션에 이미 부여한 권한을 취소하는 페이지로 연결됩니다.
  • Flask 세션 사용자 인증 정보 지우기: 이 링크는 Flask 세션에 저장된 승인 사용자 인증 정보를 지웁니다. 이를 통해 앱에 이미 권한을 부여한 사용자가 새 세션에서 API 요청을 실행하려고 하면 어떻게 되는지 확인할 수 있습니다. 또한 사용자가 앱에 부여된 권한을 취소한 경우 앱이 여전히 취소된 액세스 토큰을 사용하여 요청을 승인하려고 한 경우 앱이 얻을 수 있는 API 응답을 확인할 수 있습니다.
# -*- coding: utf-8 -*-

import os
import flask
import requests

import google.oauth2.credentials
import google_auth_oauthlib.flow
import googleapiclient.discovery

# This variable specifies the name of a file that contains the OAuth 2.0
# information for this application, including its client_id and client_secret.
CLIENT_SECRETS_FILE = "client_secret.json"

# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account and requires requests to use an SSL connection.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
API_SERVICE_NAME = 'drive'
API_VERSION = 'v2'

app = flask.Flask(__name__)
# Note: A secret key is included in the sample so that it works.
# If you use this code in your application, replace this with a truly secret
# key. See https://flask.palletsprojects.com/quickstart/#sessions.
app.secret_key = 'REPLACE ME - this value is here as a placeholder.'


@app.route('/')
def index():
  return print_index_table()


@app.route('/test')
def test_api_request():
  if 'credentials' not in flask.session:
    return flask.redirect('authorize')

  # Load credentials from the session.
  credentials = google.oauth2.credentials.Credentials(
      **flask.session['credentials'])

  drive = googleapiclient.discovery.build(
      API_SERVICE_NAME, API_VERSION, credentials=credentials)

  files = drive.files().list().execute()

  # Save credentials back to session in case access token was refreshed.
  # ACTION ITEM: In a production app, you likely want to save these
  #              credentials in a persistent database instead.
  flask.session['credentials'] = credentials_to_dict(credentials)

  return flask.jsonify(**files)


@app.route('/authorize')
def authorize():
  # Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES)

  # The URI created here must exactly match one of the authorized redirect URIs
  # for the OAuth 2.0 client, which you configured in the API Console. If this
  # value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch'
  # error.
  flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

  authorization_url, state = flow.authorization_url(
      # Enable offline access so that you can refresh an access token without
      # re-prompting the user for permission. Recommended for web server apps.
      access_type='offline',
      # Enable incremental authorization. Recommended as a best practice.
      include_granted_scopes='true')

  # Store the state so the callback can verify the auth server response.
  flask.session['state'] = state

  return flask.redirect(authorization_url)


@app.route('/oauth2callback')
def oauth2callback():
  # Specify the state when creating the flow in the callback so that it can
  # verified in the authorization server response.
  state = flask.session['state']

  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
  flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

  # Use the authorization server's response to fetch the OAuth 2.0 tokens.
  authorization_response = flask.request.url
  flow.fetch_token(authorization_response=authorization_response)

  # Store credentials in the session.
  # ACTION ITEM: In a production app, you likely want to save these
  #              credentials in a persistent database instead.
  credentials = flow.credentials
  flask.session['credentials'] = credentials_to_dict(credentials)

  return flask.redirect(flask.url_for('test_api_request'))


@app.route('/revoke')
def revoke():
  if 'credentials' not in flask.session:
    return ('You need to <a href="/authorize">authorize</a> before ' +
            'testing the code to revoke credentials.')

  credentials = google.oauth2.credentials.Credentials(
    **flask.session['credentials'])

  revoke = requests.post('https://oauth2.googleapis.com/revoke',
      params={'token': credentials.token},
      headers = {'content-type': 'application/x-www-form-urlencoded'})

  status_code = getattr(revoke, 'status_code')
  if status_code == 200:
    return('Credentials successfully revoked.' + print_index_table())
  else:
    return('An error occurred.' + print_index_table())


@app.route('/clear')
def clear_credentials():
  if 'credentials' in flask.session:
    del flask.session['credentials']
  return ('Credentials have been cleared.<br><br>' +
          print_index_table())


def credentials_to_dict(credentials):
  return {'token': credentials.token,
          'refresh_token': credentials.refresh_token,
          'token_uri': credentials.token_uri,
          'client_id': credentials.client_id,
          'client_secret': credentials.client_secret,
          'scopes': credentials.scopes}

def print_index_table():
  return ('<table>' +
          '<tr><td><a href="/test">Test an API request</a></td>' +
          '<td>Submit an API request and see a formatted JSON response. ' +
          '    Go through the authorization flow if there are no stored ' +
          '    credentials for the user.</td></tr>' +
          '<tr><td><a href="/authorize">Test the auth flow directly</a></td>' +
          '<td>Go directly to the authorization flow. If there are stored ' +
          '    credentials, you still might not be prompted to reauthorize ' +
          '    the application.</td></tr>' +
          '<tr><td><a href="/revoke">Revoke current credentials</a></td>' +
          '<td>Revoke the access token associated with the current user ' +
          '    session. After revoking credentials, if you go to the test ' +
          '    page, you should see an <code>invalid_grant</code> error.' +
          '</td></tr>' +
          '<tr><td><a href="/clear">Clear Flask session credentials</a></td>' +
          '<td>Clear the access token currently stored in the user session. ' +
          '    After clearing the token, if you <a href="/test">test the ' +
          '    API request</a> again, you should go back to the auth flow.' +
          '</td></tr></table>')


if __name__ == '__main__':
  # When running locally, disable OAuthlib's HTTPs verification.
  # ACTION ITEM for developers:
  #     When running in production *do not* leave this option enabled.
  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

  # Specify a hostname and port that are set as a valid redirect URI
  # for your API project in the Google API Console.
  app.run('localhost', 8080, debug=True)

Ruby

이 예에서는 Sinatra 프레임워크를 사용합니다.

require 'google/apis/drive_v3'
require 'sinatra'
require 'googleauth'
require 'googleauth/stores/redis_token_store'

configure do
  enable :sessions

  set :client_id, Google::Auth::ClientId.from_file('/path/to/client_secret.json')
  set :scope, Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY
  set :token_store, Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)
  set :authorizer, Google::Auth::WebUserAuthorizer.new(settings.client_id, settings.scope, settings.token_store, '/oauth2callback')
end

get '/' do
  user_id = settings.client_id.id
  credentials = settings.authorizer.get_credentials(user_id, request)
  if credentials.nil?
    redirect settings.authorizer.get_authorization_url(login_hint: user_id, request: request)
  end
  drive = Google::Apis::DriveV3::DriveService.new
  files = drive.list_files(options: { authorization: credentials })
  "<pre>#{JSON.pretty_generate(files.to_h)}</pre>"
end

get '/oauth2callback' do
  target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
  redirect target_url
end

Node.js

이 예시를 실행하려면 다음 안내를 따르세요.

  1. API Console에서 로컬 머신의 URL을 리디렉션 URL 목록에 추가합니다. 예를 들어 http://localhost를 추가합니다.
  2. 유지보수 LTS, 활성 LTS 또는 Node.js의 현재 출시 버전이 설치되어 있는지 확인하세요.
  3. 새 디렉터리를 만들어 해당 디렉터리로 변경합니다. 예를 들면 다음과 같습니다.
    mkdir ~/nodejs-oauth2-example
    cd ~/nodejs-oauth2-example
  4. Install the Google API Client Library for Node.js using npm:
    npm install googleapis
  5. 아래 콘텐츠로 main.js 파일을 만듭니다.
  6. 예를 실행합니다.
    node .\main.js

main.js

const http = require('http');
const https = require('https');
const url = require('url');
const { google } = require('googleapis');

/**
 * To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI.
 * To get these credentials for your application, visit
 * https://console.cloud.google.com/apis/credentials.
 */
const oauth2Client = new google.auth.OAuth2(
  YOUR_CLIENT_ID,
  YOUR_CLIENT_SECRET,
  YOUR_REDIRECT_URL
);

// Access scopes for read-only Drive activity.
const scopes = [
  'https://www.googleapis.com/auth/drive.metadata.readonly'
];

// Generate a url that asks permissions for the Drive activity scope
const authorizationUrl = oauth2Client.generateAuthUrl({
  // 'online' (default) or 'offline' (gets refresh_token)
  access_type: 'offline',
  /** Pass in the scopes array defined above.
    * Alternatively, if only one scope is needed, you can pass a scope URL as a string */
  scope: scopes,
  // Enable incremental authorization. Recommended as a best practice.
  include_granted_scopes: true
});

/* Global variable that stores user credential in this code example.
 * ACTION ITEM for developers:
 *   Store user's refresh token in your data store if
 *   incorporating this code into your real app.
 *   For more information on handling refresh tokens,
 *   see https://github.com/googleapis/google-api-nodejs-client#handling-refresh-tokens
 */
let userCredential = null;

async function main() {
  const server = http.createServer(async function (req, res) {
    // Example on redirecting user to Google's OAuth 2.0 server.
    if (req.url == '/') {
      res.writeHead(301, { "Location": authorizationUrl });
    }

    // Receive the callback from Google's OAuth 2.0 server.
    if (req.url.startsWith('/oauth2callback')) {
      // Handle the OAuth 2.0 server response
      let q = url.parse(req.url, true).query;

      if (q.error) { // An error response e.g. error=access_denied
        console.log('Error:' + q.error);
      } else { // Get access and refresh tokens (if access_type is offline)
        let { tokens } = await oauth2Client.getToken(q.code);
        oauth2Client.setCredentials(tokens);

        /** Save credential to the global variable in case access token was refreshed.
          * ACTION ITEM: In a production app, you likely want to save the refresh token
          *              in a secure persistent database instead. */
        userCredential = tokens;

        // Example of using Google Drive API to list filenames in user's Drive.
        const drive = google.drive('v3');
        drive.files.list({
          auth: oauth2Client,
          pageSize: 10,
          fields: 'nextPageToken, files(id, name)',
        }, (err1, res1) => {
          if (err1) return console.log('The API returned an error: ' + err1);
          const files = res1.data.files;
          if (files.length) {
            console.log('Files:');
            files.map((file) => {
              console.log(`${file.name} (${file.id})`);
            });
          } else {
            console.log('No files found.');
          }
        });
      }
    }

    // Example on revoking a token
    if (req.url == '/revoke') {
      // Build the string for the POST request
      let postData = "token=" + userCredential.access_token;

      // Options for POST request to Google's OAuth 2.0 server to revoke a token
      let postOptions = {
        host: 'oauth2.googleapis.com',
        port: '443',
        path: '/revoke',
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(postData)
        }
      };

      // Set up the request
      const postReq = https.request(postOptions, function (res) {
        res.setEncoding('utf8');
        res.on('data', d => {
          console.log('Response: ' + d);
        });
      });

      postReq.on('error', error => {
        console.log(error)
      });

      // Post the request with data
      postReq.write(postData);
      postReq.end();
    }
    res.end();
  }).listen(80);
}
main().catch(console.error);

HTTP/REST

이 Python 예시에서는 Flask 프레임워크와 Requests 라이브러리를 사용하여 OAuth 2.0 웹 흐름을 보여줍니다. 이 과정에서 Python용 Google API 클라이언트 라이브러리를 사용하는 것이 좋습니다. Python 탭의 예시에서는 클라이언트 라이브러리를 사용합니다.

import json

import flask
import requests


app = flask.Flask(__name__)

CLIENT_ID = '123456789.apps.googleusercontent.com'
CLIENT_SECRET = 'abc123'  # Read from a file or environmental variable in a real app
SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly'
REDIRECT_URI = 'http://example.com/oauth2callback'


@app.route('/')
def index():
  if 'credentials' not in flask.session:
    return flask.redirect(flask.url_for('oauth2callback'))
  credentials = json.loads(flask.session['credentials'])
  if credentials['expires_in'] <= 0:
    return flask.redirect(flask.url_for('oauth2callback'))
  else:
    headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
    req_uri = 'https://www.googleapis.com/drive/v2/files'
    r = requests.get(req_uri, headers=headers)
    return r.text


@app.route('/oauth2callback')
def oauth2callback():
  if 'code' not in flask.request.args:
    auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
                '&client_id={}&redirect_uri={}&scope={}').format(CLIENT_ID, REDIRECT_URI, SCOPE)
    return flask.redirect(auth_uri)
  else:
    auth_code = flask.request.args.get('code')
    data = {'code': auth_code,
            'client_id': CLIENT_ID,
            'client_secret': CLIENT_SECRET,
            'redirect_uri': REDIRECT_URI,
            'grant_type': 'authorization_code'}
    r = requests.post('https://oauth2.googleapis.com/token', data=data)
    flask.session['credentials'] = r.text
    return flask.redirect(flask.url_for('index'))


if __name__ == '__main__':
  import uuid
  app.secret_key = str(uuid.uuid4())
  app.debug = False
  app.run()

리디렉션 URI 유효성 검사 규칙

Google은 개발자가 애플리케이션을 안전하게 유지할 수 있도록 다음과 같은 유효성 검사 규칙을 리디렉션 URI에 적용합니다. 리디렉션 URI는 이러한 규칙을 준수해야 합니다. 아래에 언급된 도메인, 호스트, 경로, 쿼리, 스키마, 사용자 정보의 정의는 RFC 3986 섹션 3을 참고하세요.

유효성 검사 규칙
스키마

리디렉션 URI는 일반 HTTP가 아닌 HTTPS 스키마를 사용해야 합니다. 로컬 호스트 URI (localhost IP 주소 URI 포함)는 이 규칙에서 제외됩니다.

호스트

호스트는 원시 IP 주소일 수 없습니다. 로컬 호스트 IP 주소는 이 규칙에서 제외됩니다.

도메인
  • 호스트 TLD(최상위 도메인)는 공개 서픽스 목록에 속해야 합니다.
  • 호스트 도메인은 “googleusercontent.com”일 수 없습니다.
  • 앱이 도메인을 소유하지 않는 한 리디렉션 URI는 URL 단축 도메인 (예: goo.gl)을 포함할 수 없습니다. 또한 단축 도메인을 소유한 앱에서 해당 도메인으로 리디렉션하도록 선택하면 리디렉션 URI의 경로에 “/google-callback/”가 포함되거나 “/google-callback”로 끝나야 합니다.
  • 사용자 정보

    리디렉션 URI는 userinfo 하위 구성요소를 포함할 수 없습니다.

    경로

    리디렉션 URI는 “/..” 또는 “\..” 또는 URL 인코딩으로 표시되는 경로 순회 (디렉터리 역추적이라고도 함)를 포함할 수 없습니다.

    쿼리

    리디렉션 URI에는 열린 리디렉션이 포함될 수 없습니다.

    Fragment

    리디렉션 URI는 프래그먼트 구성요소를 포함할 수 없습니다.

    문자 리디렉션 URI에는 다음과 같은 특정 문자를 포함할 수 없습니다.
    • 와일드 카드 문자 ('*')
    • 인쇄할 수 없는 ASCII 문자
    • 퍼센트 인코딩이 잘못되었습니다. URL 인코딩 형식을 따라 퍼센트 기호 다음에 16진수 두 자리가 오지 않는 퍼센트 인코딩입니다.
    • null 문자 (인코딩된 NULL 문자, 예: %00, %C0%80)

    증분 승인

    OAuth 2.0 프로토콜에서는 앱이 범위로 식별되는 리소스에 액세스할 수 있는 권한을 요청합니다. 사용자 환경이 필요할 때 리소스 승인을 요청하는 것이 좋습니다. 이를 위해 Google 승인 서버에서 점진적 승인을 지원합니다. 이 기능을 사용하면 필요에 따라 범위를 요청할 수 있으며, 사용자가 새 범위에 대한 권한을 부여하면 사용자가 프로젝트에 부여한 모든 범위가 포함된 토큰으로 교환할 수 있는 승인 코드를 반환합니다.

    예를 들어 사용자가 음악 트랙을 샘플링하고 믹스를 만들 수 있는 앱은 로그인 시 필요한 리소스가 거의 없으며, 로그인하는 사용자의 이름만 있으면 됩니다. 하지만 완료된 믹스를 저장하려면 Google 드라이브에 액세스해야 합니다. 앱에 실제로 액세스가 필요할 때만 Google Drive 액세스 권한을 요청받았다면 대부분의 사람들은 자연스러운 것이라고 생각할 것입니다.

    이 경우 로그인 시 앱은 기본 로그인을 수행하도록 openidprofile 범위를 요청한 다음 나중에 첫 번째 요청 시 https://www.googleapis.com/auth/drive.file 범위를 요청하여 믹스를 저장할 수 있습니다.

    증분 승인을 구현하려면 액세스 토큰을 요청하는 일반적인 흐름을 완료하되 승인 요청에 이전에 부여된 범위가 포함되어 있는지 확인합니다. 이 방법을 사용하면 앱에서 여러 개의 액세스 토큰을 관리하지 않아도 됩니다.

    증분 승인에서 얻은 액세스 토큰에는 다음 규칙이 적용됩니다.

    • 토큰을 사용하여 결합된 새로운 승인에 적용된 모든 범위에 해당하는 리소스에 액세스할 수 있습니다.
    • 결합된 승인에 갱신 토큰을 사용하여 액세스 토큰을 가져오는 경우 액세스 토큰은 결합된 승인을 나타내며 응답에 포함된 모든 scope 값에 사용할 수 있습니다.
    • 결합된 승인에는 권한 부여가 다른 클라이언트에서 요청되었더라도 사용자가 API 프로젝트에 부여한 모든 범위가 포함됩니다. 예를 들어 사용자가 애플리케이션의 데스크톱 클라이언트를 사용하여 한 범위에 대한 액세스 권한을 부여하고 모바일 클라이언트를 통해 동일한 애플리케이션에 다른 범위를 부여한 경우 결합된 승인에 두 범위가 모두 포함됩니다.
    • 결합된 승인을 나타내는 토큰을 취소하면 연결된 사용자를 대신하여 모든 승인 범위에 대한 액세스 권한이 동시에 취소됩니다.

    1단계: 승인 매개변수 설정의 언어별 코드 샘플과 2단계: Google의 OAuth 2.0 서버로 리디렉션의 샘플 HTTP/REST 리디렉션 URL은 모두 증분 승인을 사용합니다. 아래의 코드 샘플에는 점진적 승인을 사용하기 위해 추가해야 하는 코드도 나와 있습니다.

    2,399필리핀

    $client->setIncludeGrantedScopes(true);

    Python

    Python에서 include_granted_scopes 키워드 인수를 true로 설정하여 이전에 부여된 범위가 승인 요청에 포함되도록 합니다. 아래 예와 같이 include_granted_scopes가 설정된 유일한 키워드 인수가 아닐 가능성이 매우 있습니다.

    authorization_url, state = flow.authorization_url(
        # Enable offline access so that you can refresh an access token without
        # re-prompting the user for permission. Recommended for web server apps.
        access_type='offline',
        # Enable incremental authorization. Recommended as a best practice.
        include_granted_scopes='true')

    Ruby

    auth_client.update!(
      :additional_parameters => {"include_granted_scopes" => "true"}
    )

    Node.js

    const authorizationUrl = oauth2Client.generateAuthUrl({
      // 'online' (default) or 'offline' (gets refresh_token)
      access_type: 'offline',
      /** Pass in the scopes array defined above.
        * Alternatively, if only one scope is needed, you can pass a scope URL as a string */
      scope: scopes,
      // Enable incremental authorization. Recommended as a best practice.
      include_granted_scopes: true
    });
    

    HTTP/REST

    GET https://accounts.google.com/o/oauth2/v2/auth?
      client_id=your_client_id&
      response_type=code&
      state=state_parameter_passthrough_value&
      scope=https%3A//www.googleapis.com/auth/drive.file&
      redirect_uri=https%3A//oauth2.example.com/code&
      prompt=consent&
      include_granted_scopes=true

    액세스 토큰 갱신 (오프라인 액세스)

    액세스 토큰은 주기적으로 만료되어 관련 API 요청에 대해 유효하지 않은 사용자 인증 정보가 됩니다. 토큰과 연결된 범위에 대한 오프라인 액세스를 요청한 경우 사용자에게 권한을 요청하지 않고 액세스 토큰을 새로고침할 수 있습니다 (사용자가 없을 때 포함).

    • Google API 클라이언트 라이브러리를 사용하는 경우 오프라인 액세스를 위해 객체를 구성하면 클라이언트 객체가 필요에 따라 액세스 토큰을 새로고침합니다.
    • 클라이언트 라이브러리를 사용하지 않는다면 사용자를 Google의 OAuth 2.0 서버로 리디렉션할 때 access_type HTTP 쿼리 매개변수를 offline로 설정해야 합니다. 이 경우 승인 코드를 액세스 토큰으로 교환하면 Google 승인 서버에서 갱신 토큰을 반환합니다. 그런 다음 액세스 토큰이 만료되면 (또는 다른 시점에) 갱신 토큰을 사용하여 새 액세스 토큰을 얻을 수 있습니다.

    오프라인 액세스 요청은 사용자가 없을 때 Google API에 액세스해야 하는 모든 애플리케이션의 요구사항입니다. 예를 들어 백업 서비스를 실행하거나 미리 정해진 시간에 작업을 실행하는 앱은 사용자가 없을 때 액세스 토큰을 새로고침할 수 있어야 합니다. 기본 액세스 스타일은 online입니다.

    서버 측 웹 애플리케이션, 설치된 애플리케이션, 기기는 모두 승인 프로세스 중에 갱신 토큰을 받습니다. 갱신 토큰은 일반적으로 클라이언트 측(자바스크립트) 웹 애플리케이션에서 사용되지 않습니다.

    2,399필리핀

    애플리케이션에서 Google API에 오프라인으로 액세스해야 한다면 API 클라이언트의 액세스 유형을 offline로 설정합니다.

    $client->setAccessType("offline");

    사용자가 요청된 범위에 대한 오프라인 액세스 권한을 부여한 후에는 사용자가 오프라인 상태일 때 관리자가 API 클라이언트를 사용하여 사용자 대신 Google API에 액세스할 수 있습니다. 클라이언트 객체는 필요에 따라 액세스 토큰을 새로고침합니다.

    Python

    Python에서 access_type 키워드 인수를 offline로 설정하면 사용자에게 권한을 다시 요청하지 않고도 액세스 토큰을 새로고침할 수 있습니다. 아래 예와 같이 access_type가 설정한 유일한 키워드 인수가 아닐 가능성이 매우 있습니다.

    authorization_url, state = flow.authorization_url(
        # Enable offline access so that you can refresh an access token without
        # re-prompting the user for permission. Recommended for web server apps.
        access_type='offline',
        # Enable incremental authorization. Recommended as a best practice.
        include_granted_scopes='true')

    사용자가 요청된 범위에 대한 오프라인 액세스 권한을 부여한 후에는 사용자가 오프라인 상태일 때 관리자가 API 클라이언트를 사용하여 사용자 대신 Google API에 액세스할 수 있습니다. 클라이언트 객체는 필요에 따라 액세스 토큰을 새로고침합니다.

    Ruby

    애플리케이션에서 Google API에 오프라인으로 액세스해야 한다면 API 클라이언트의 액세스 유형을 offline로 설정합니다.

    auth_client.update!(
      :additional_parameters => {"access_type" => "offline"}
    )

    사용자가 요청된 범위에 대한 오프라인 액세스 권한을 부여한 후에는 사용자가 오프라인 상태일 때 관리자가 API 클라이언트를 사용하여 사용자 대신 Google API에 액세스할 수 있습니다. 클라이언트 객체는 필요에 따라 액세스 토큰을 새로고침합니다.

    Node.js

    애플리케이션에서 Google API에 오프라인으로 액세스해야 한다면 API 클라이언트의 액세스 유형을 offline로 설정합니다.

    const authorizationUrl = oauth2Client.generateAuthUrl({
      // 'online' (default) or 'offline' (gets refresh_token)
      access_type: 'offline',
      /** Pass in the scopes array defined above.
        * Alternatively, if only one scope is needed, you can pass a scope URL as a string */
      scope: scopes,
      // Enable incremental authorization. Recommended as a best practice.
      include_granted_scopes: true
    });
    

    사용자가 요청된 범위에 대한 오프라인 액세스 권한을 부여한 후에는 사용자가 오프라인 상태일 때 관리자가 API 클라이언트를 사용하여 사용자 대신 Google API에 액세스할 수 있습니다. 클라이언트 객체는 필요에 따라 액세스 토큰을 새로고침합니다.

    액세스 토큰은 만료됩니다. 이 라이브러리는 액세스 토큰이 만료될 때가 되면 자동으로 갱신 토큰을 사용하여 새 액세스 토큰을 얻습니다. 항상 최신 토큰을 저장하는 쉬운 방법은 토큰 이벤트를 사용하는 것입니다.

    oauth2Client.on('tokens', (tokens) => {
      if (tokens.refresh_token) {
        // store the refresh_token in your secure persistent database
        console.log(tokens.refresh_token);
      }
      console.log(tokens.access_token);
    });

    이 토큰 이벤트는 첫 번째 승인 시에만 발생하며, 갱신 토큰을 받기 위해 generateAuthUrl 메서드를 호출할 때 access_typeoffline로 설정해야 합니다. 갱신 토큰 수신에 대한 적절한 제약조건을 설정하지 않고 이미 앱에 필요한 권한을 부여한 경우 새 갱신 토큰을 받도록 애플리케이션을 다시 승인해야 합니다.

    나중에 refresh_token를 설정하려면 setCredentials 메서드를 사용하면 됩니다.

    oauth2Client.setCredentials({
      refresh_token: `STORED_REFRESH_TOKEN`
    });
    

    클라이언트에 갱신 토큰이 있으면 다음번 API 호출 시 액세스 토큰이 자동으로 획득 및 갱신됩니다.

    HTTP/REST

    액세스 토큰을 갱신하려면 애플리케이션에서 다음 매개변수가 포함된 HTTPS POST 요청을 Google 승인 서버 (https://oauth2.googleapis.com/token)로 전송합니다.

    입력란
    client_id API Console에서 가져온 클라이언트 ID입니다.
    client_secret API Console에서 가져온 클라이언트 보안 비밀번호입니다.
    grant_type OAuth 2.0 사양에 정의된 대로 이 필드의 값은 refresh_token로 설정해야 합니다.
    refresh_token 승인 코드 교환에서 반환된 갱신 토큰입니다.

    다음 스니펫은 샘플 요청을 보여줍니다.

    POST /token HTTP/1.1
    Host: oauth2.googleapis.com
    Content-Type: application/x-www-form-urlencoded
    
    client_id=your_client_id&
    client_secret=your_client_secret&
    refresh_token=refresh_token&
    grant_type=refresh_token

    사용자가 애플리케이션에 부여된 액세스 권한을 취소하지 않는 한 토큰 서버는 새 액세스 토큰이 포함된 JSON 객체를 반환합니다. 다음 스니펫은 샘플 응답을 보여줍니다.

    {
      "access_token": "1/fFAGRNJru1FTz70BzhT3Zg",
      "expires_in": 3920,
      "scope": "https://www.googleapis.com/auth/drive.metadata.readonly",
      "token_type": "Bearer"
    }

    발급되는 갱신 토큰 수에는 한도가 있습니다. 클라이언트/사용자 조합당 한도 1개, 모든 클라이언트에서 사용자당 한도 1개입니다. 갱신 토큰을 장기 저장소에 저장하여 유효할 때까지 계속 사용해야 합니다. 애플리케이션에서 너무 많은 갱신 토큰을 요청하면 이러한 한도에 도달할 수 있으며, 이 경우 이전 갱신 토큰이 작동하지 않습니다.

    토큰 취소

    사용자가 애플리케이션에 부여된 액세스 권한을 취소하고자 하는 경우도 있습니다. 사용자는 계정 설정을 방문하여 액세스 권한을 취소할 수 있습니다. 자세한 내용은 내 계정에 액세스할 수 있는 서드 파티 사이트 및 앱의 사이트 또는 앱 액세스 권한 삭제 섹션 지원 문서를 참고하세요.

    또한 애플리케이션에 부여된 액세스 권한을 프로그래밍 방식으로 취소할 수도 있습니다. 프로그래매틱 취소는 사용자가 구독을 취소하거나 애플리케이션을 삭제하거나 앱에 필요한 API 리소스가 크게 변경된 경우에 중요합니다. 즉, 이전에 애플리케이션에 부여되었던 권한이 삭제되도록 하기 위한 API 요청이 삭제 프로세스에 포함될 수 있습니다.

    2,399필리핀

    프로그래매틱 방식으로 토큰을 취소하려면 revokeToken()를 호출합니다.

    $client->revokeToken();

    Python

    프로그래매틱 방식으로 토큰을 취소하려면 토큰을 매개변수로 포함하고 Content-Type 헤더를 설정하는 https://oauth2.googleapis.com/revoke에 요청합니다.

    requests.post('https://oauth2.googleapis.com/revoke',
        params={'token': credentials.token},
        headers = {'content-type': 'application/x-www-form-urlencoded'})

    Ruby

    프로그래매틱 방식으로 토큰을 취소하려면 oauth2.revoke 엔드포인트에 대해 HTTP 요청을 실행합니다.

    uri = URI('https://oauth2.googleapis.com/revoke')
    response = Net::HTTP.post_form(uri, 'token' => auth_client.access_token)
    

    토큰은 액세스 토큰 또는 갱신 토큰일 수 있습니다. 토큰이 액세스 토큰이고 해당하는 갱신 토큰이 있는 경우 갱신 토큰도 취소됩니다.

    취소가 성공적으로 처리되면 응답의 상태 코드는 200입니다. 오류 조건의 경우 상태 코드 400가 오류 코드와 함께 반환됩니다.

    Node.js

    프로그래매틱 방식으로 토큰을 취소하려면 /revoke 엔드포인트에 HTTPS POST 요청을 실행합니다.

    const https = require('https');
    
    // Build the string for the POST request
    let postData = "token=" + userCredential.access_token;
    
    // Options for POST request to Google's OAuth 2.0 server to revoke a token
    let postOptions = {
      host: 'oauth2.googleapis.com',
      port: '443',
      path: '/revoke',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData)
      }
    };
    
    // Set up the request
    const postReq = https.request(postOptions, function (res) {
      res.setEncoding('utf8');
      res.on('data', d => {
        console.log('Response: ' + d);
      });
    });
    
    postReq.on('error', error => {
      console.log(error)
    });
    
    // Post the request with data
    postReq.write(postData);
    postReq.end();
    

    토큰 매개변수는 액세스 토큰 또는 갱신 토큰일 수 있습니다. 토큰이 액세스 토큰이고 해당하는 갱신 토큰이 있는 경우 갱신 토큰도 취소됩니다.

    취소가 성공적으로 처리되면 응답의 상태 코드는 200입니다. 오류 조건의 경우 상태 코드 400가 오류 코드와 함께 반환됩니다.

    HTTP/REST

    프로그래매틱 방식으로 토큰을 취소하기 위해 애플리케이션이 https://oauth2.googleapis.com/revoke에 요청하고 토큰을 매개변수로 포함합니다.

    curl -d -X -POST --header "Content-type:application/x-www-form-urlencoded" \
            https://oauth2.googleapis.com/revoke?token={token}

    토큰은 액세스 토큰 또는 갱신 토큰일 수 있습니다. 토큰이 액세스 토큰이며 해당 갱신 토큰이 있는 경우 갱신 토큰도 취소됩니다.

    취소가 성공적으로 처리되면 응답의 HTTP 상태 코드는 200입니다. 오류 조건의 경우 HTTP 상태 코드 400가 오류 코드와 함께 반환됩니다.