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

이 문서에서는 웹 서버 애플리케이션이 Google API 클라이언트 라이브러리 또는 Google 액세스를 위한 OAuth 2.0 승인을 구현하는 OAuth 2.0 엔드포인트 Google API

OAuth 2.0을 통해 사용자는 애플리케이션을 유지하면서 애플리케이션 및 특정 데이터를 공유할 수 있습니다. 사용자 이름, 비밀번호 및 기타 정보를 비공개로 유지합니다. 예를 들어 애플리케이션은 OAuth 2.0을 사용하여 Google Drive에 파일을 저장할 수 있습니다.

이 OAuth 2.0 흐름은 특별히 사용자 인증용입니다. 애플리케이션을 위해 설계되었으며 상태를 유지관리할 수 있는 Cloud Run이 있습니다 제대로 인증된 웹 서버 사용자가 애플리케이션과 상호작용하는 동안이나 사용자가 상호작용한 후에 애플리케이션에서 API에 액세스할 수 있음 애플리케이션을 종료했습니다.

웹 서버 응용 프로그램은 흔히 서비스 계정을 사용하여 API 요청을 승인합니다(특히 Cloud API를 호출하여 액세스하는 경우). 사용자별 데이터가 아닌 프로젝트 기반 데이터를 저장하는 데 도움이 됩니다 웹 서버 애플리케이션은 계정에 적용됩니다.

클라이언트 라이브러리

이 페이지의 언어별 예에서는 구현할 Google API 클라이언트 라이브러리 OAuth 2.0 승인. 코드 샘플을 실행하려면 먼저 클라이언트 라이브러리를 사용할 수 있습니다.

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

서버 측 애플리케이션용 Google API 클라이언트 라이브러리는 다음 언어로 사용할 수 있습니다.

기본 요건

프로젝트에 API 사용 설정

Google API를 호출하는 모든 애플리케이션은 API Console

프로젝트에 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가 목록에 표시되지 않으면 검색을 사용하여 제품을 찾거나 제품이 속한 제품군에서 모두 보기를 클릭합니다.
  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, Java, Python, Ruby, .NET 등에서 승인된 리디렉션 URI를 지정해야 합니다. 이 리디렉션 URI는 OAuth 2.0 서버가 응답을 보낼 수 있는 엔드포인트입니다. 이러한 엔드포인트는 Google의 유효성 검사 규칙을 준수해야 합니다.

    테스트를 위해 다음과 같이 로컬 컴퓨터를 참조하는 URI를 지정할 수 있습니다. http://localhost:8080 이를 염두에 두고 이 문서의 예에서는 http://localhost:8080를 리디렉션 URI로 사용합니다.

    따라서 사용자가 인증한 정보를 인증하기 위해 앱의 인증 엔드포인트를 설계하여 애플리케이션이 인증 코드를 있습니다.

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

액세스 범위 식별

범위를 사용 설정하면 애플리케이션이 필요한 리소스에 대한 액세스만 요청할 수 있으며 사용자가 애플리케이션에 부여하는 액세스 수준을 제어할 수 있게 해줍니다. 따라서 요청된 범위 수와 사용자 동의 획득

OAuth 2.0 승인을 구현하기 전에 해당 범위를 식별하는 것이 좋습니다. 앱에 액세스 권한이 있어야 합니다

또한 애플리케이션에서 증분 승인 프로세스를 거쳐야 합니다. 컨텍스트 안에서 사용자 데이터에 대한 액세스를 요청합니다. 이 권장사항은 사용자가 애플리케이션에 요청하는 액세스 권한이 필요한 이유도 확인할 수 있습니다.

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

언어별 요구사항

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

PHP

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

  • 명령줄 인터페이스 (CLI) 및 JSON 확장 프로그램이 설치된 PHP 5.6 이상
  • 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 crypto express express-session

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을 생성하고 매개변수를 사용할 수 있습니다.

아래 탭에서는 웹 서버 애플리케이션에 대해 지원되는 승인 매개변수를 정의합니다. 이 언어별 예제도 클라이언트 라이브러리 또는 승인 라이브러리를 사용하여 해당 매개변수를 설정하는 객체를 구성할 수 있습니다

PHP

아래 코드 스니펫은 Google\Client() 객체를 만듭니다. 이 객체는 매개변수를 포함해야 합니다.

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

예를 들어 이 코드는 사용자의 Google 드라이브:

$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 모듈을 사용하여 승인 요청을 보냅니다.

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

예를 들어 이 코드는 사용자의 Google 드라이브:

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',
    # 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 파일을 사용하여 애플리케이션입니다. 클라이언트 객체를 구성할 때 애플리케이션이 필요로 하는 범위를 지정합니다. 응답을 처리할 애플리케이션 인증 엔드포인트의 URL과 함께 OAuth 2.0 서버에서 가져옵니다.

예를 들어 이 코드는 사용자의 Google 드라이브:

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')

애플리케이션은 클라이언트 객체를 사용하여 OAuth 2.0 작업(예: HTTP 요청에 액세스 토큰을 적용할 수 있습니다.

Node.js

다음 코드 스니펫은 google.auth.OAuth2 객체를 만들고 이 객체는 매개변수를 포함해야 합니다.

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

const {google} = require('googleapis');
const crypto = require('crypto');
const express = require('express');
const session = require('express-session');

/**
 * 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 secure random state value.
const state = crypto.randomBytes(32).toString('hex');

// Store state in the session
req.session.state = state;

// 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,
  // Include the state parameter to reduce the risk of CSRF attacks.
  state: state
});

중요 사항 - 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 필수

사용자가 사용할 수 있습니다. 값은 OAuth 2.0 클라이언트 ID를 가져올 수도 있습니다. API Console Credentials page입니다. 이 값이 제공된 client_id에 대해 승인된 리디렉션 URI를 반환합니다. redirect_uri_mismatch 오류가 발생했습니다.

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

response_type 필수

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

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

scope 필수

가 공백으로 구분 애플리케이션이 액세스할 수 있는 리소스를 식별하는 범위 할 수 있습니다. 이 값은 Google에서 있습니다.

범위를 사용하면 애플리케이션이 필요한 리소스에 대한 액세스만 요청할 수 있습니다. 사용자가 내 사이트에 부여하는 액세스 권한의 양을 애플리케이션입니다. 따라서 요청된 범위 수 간에는 반비례 관계가 있습니다. 사용자 동의 획득 가능성을 고려합니다.

애플리케이션에서 컨텍스트 내에서 승인 범위에 대한 액세스를 요청하는 것이 좋습니다. 할 수 있습니다. 다음을 통해 컨텍스트 내에서 사용자 데이터에 대한 액세스를 요청함 단계별 승인을 통해 사용자가 손쉽게 애플리케이션에 요청하는 액세스가 필요한 이유를 이해할 수 있습니다.

access_type 권장

사용자가 없을 때 애플리케이션이 액세스 토큰을 갱신할 수 있는지 여부를 나타냅니다. 할 수 있습니다. 유효한 매개변수 값은 기본값인 online입니다. 값, offline.

애플리케이션에서 액세스 토큰을 새로고침해야 하는 경우 값을 offline로 설정합니다. 사용자가 브라우저에 없을 때 액세스 권한을 새로고침하는 방법입니다. 이 문서의 뒷부분에서 설명하겠습니다 이 값은 그리고 액세스 토큰을 반환하도록 인증 코드를 토큰으로 교환합니다.

state 권장

애플리케이션이 승인 요청 및 승인 서버의 응답을 나타냅니다. 서버는 name=value 쌍으로 전송하는 정확한 값을 다음 URL의 쿼리 구성요소 (?)는 redirect_uri 사용자가 애플리케이션의 액세스할 수 있습니다.

이 매개변수는 사용자를 nonce 전송, 교차 사이트 요청 완화 등 애플리케이션의 올바른 리소스 사용 있습니다. state를 사용하여 redirect_uri을 추측할 수 있으므로 값은 수신 연결이 18개월 또는 30일 동안의 인증 요청에 사용할 수 있습니다. 임의의 문자열을 생성하거나 쿠키 또는 쿠키의 해시를 인코딩하는 경우 클라이언트 상태를 캡처하는 다른 값이 있는 경우 요청과 응답이 동일한 브라우저에서 시작되었는지 확인해야 합니다. 일회성, 직간접적 공격, 지속적 공격, 크로스 사이트 요청 위조 자세한 내용은 OpenID Connect state 토큰을 만들고 확인하는 방법에 관한 예시를 참조하세요.

include_granted_scopes 선택사항

애플리케이션이 점진적 승인을 사용하여 추가 범위를 맞춤설정할 수 있습니다 이 매개변수의 값을 true로 설정하고 승인 요청이 승인되면 새 액세스 토큰에 이전에 애플리케이션 액세스 권한을 부여한 것입니다. 자세한 내용은 증분 승인 섹션을 참조하세요.

login_hint 선택사항

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

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

prompt 선택사항

공백으로 구분되며 대소문자를 구분하는 사용자에게 표시할 메시지 목록입니다. 그렇지 않은 경우 이 매개변수를 지정하면 프로젝트를 처음 사용할 때만 사용자에게 메시지가 표시됩니다. 에서 액세스를 요청합니다. 를 참조하세요. 재동의 메시지 표시

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

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

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

인증 및 인증 절차를 시작할 수 있도록 사용자를 Google의 OAuth 2.0 서버로 리디렉션합니다. 승인 프로세스를 시작합니다. 일반적으로 이 문제는 애플리케이션이 처음에 사용자 데이터를 수집합니다. 증분 승인의 경우 다음과 같습니다. 추가 리소스에 액세스해야 할 때도 아직 액세스 권한이 없습니다.

PHP

  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단계에서 생성된 URL(authorizationUrl)을 사용합니다. generateAuthUrl 메서드를 사용하여 Google의 OAuth 2.0 서버에서 액세스를 요청합니다.
  2. 사용자를 authorizationUrl로 리디렉션합니다.
    res.redirect(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 서버는 사용자를 인증하고 이 API를 사용하여 요청된 범위에 액세스할 수 있습니다. 응답은 애플리케이션으로 다시 전송됩니다. 지정된 리디렉션 URL을 사용합니다.

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

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

애플리케이션은 이 단계에서 액세스 권한이 부여되었는지 여부를 나타내는 Google의 OAuth 2.0 서버입니다. 이 응답은 다음 단계를 따르세요.

오류

Google의 OAuth 2.0 승인 엔드포인트에 대한 요청에서 사용자에게 표시되는 오류 메시지를 표시할 수 있습니다. 를 사용합니다. 일반적인 오류 코드 및 추천 해결 방법은 아래에 나와 있습니다.

admin_policy_enforced

Google 계정에서 다음 정책으로 인해 요청된 하나 이상의 범위를 승인할 수 없습니다. Google Workspace 관리자에게 문의하세요 Google Workspace 관리자 도움말 보기 어떤 서드 파티 및 Google Workspace 데이터에 액세스하는 내부 앱 를 참조하세요. OAuth 클라이언트 ID에 액세스 권한이 명시적으로 부여될 때까지 범위를 제한합니다.

disallowed_useragent

승인 엔드포인트는 Google에서 허용하지 않는 삽입된 user-agent 내부에 표시되며 OAuth 2.0 정책

Android

Android 개발자가 android.webkit.WebView 개발자는 대신 다음과 같은 Android 라이브러리를 사용해야 합니다. Android용 Google 로그인 또는 OpenID Foundation Android용 AppAuth.

Android 앱이 추가된 사용자 에이전트 및 사용자가 Google OAuth 2.0 승인 엔드포인트로 이동한 다음 확인할 수 있습니다. 개발자는 일반 링크가 운영체제의 일부로 Android App Links 핸들러 또는 기본 브라우저 앱을 사용할 수 있습니다. 이 Android 맞춤 탭 라이브러리도 지원되는 옵션입니다.

iOS

iOS 및 macOS 개발자가 WKWebView 개발자는 대신 다음과 같은 iOS 라이브러리를 사용해야 합니다. iOS용 Google 로그인 또는 OpenID Foundation iOS용 AppAuth.

iOS 또는 macOS 앱에서 삽입된 사용자 에이전트 및 사용자가 Google의 OAuth 2.0 승인 엔드포인트로 이동하여 확인할 수 있습니다. 개발자는 일반 링크가 운영체제의 일부로 범용 링크 핸들러 또는 기본 브라우저 앱을 사용할 수 있습니다. 이 SFSafariViewController 라이브러리도 지원되는 옵션입니다.

org_internal

요청에 포함된 OAuth 클라이언트 ID가 구체적인 Google Cloud 조직. 이 구성 옵션에 대한 자세한 내용은 사용자 유형 섹션을 참조하세요.

invalid_client

OAuth 클라이언트 보안 비밀번호가 잘못되었습니다. 검토: OAuth 클라이언트 구성이 포함됩니다.

invalid_grant

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

redirect_uri_mismatch

승인 요청에서 전달된 redirect_uri이(가) 승인된 OAuth 클라이언트 ID의 리디렉션 URI입니다. 승인된 리디렉션 URI는 Google API Console Credentials page

redirect_uri 매개변수는 더 이상 지원되지 않습니다 자세한 내용은 이전 가이드를 참고하여 통합할 수 있습니다

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 서버 응답 샘플

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

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 오류가 발생합니다. 이 다음 단계에서는 사용자가 애플리케이션으로 다시 리디렉션됩니다

5단계: 새로고침 및 액세스를 위해 승인 코드 교환 토큰

웹 서버가 승인 코드를 수신한 후 승인 코드를 교환할 수 있습니다. 액세스할 수 있습니다

PHP

승인 코드를 액세스 토큰으로 교환하려면 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.
app.get('/oauth2callback', async (req, res) => {
  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 if (q.state !== req.session.state) { //check state value
    console.log('State mismatch. Possible CSRF attack');
    res.end('State mismatch. Possible CSRF attack');
  } else { // 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 API Console에서 가져온 클라이언트 ID Credentials page입니다.
client_secret API Console에서 가져온 클라이언트 보안 비밀번호 Credentials page입니다.
code 초기 요청에서 반환된 승인 코드입니다.
grant_type OAuth 2.0 사양이면 이 필드의 값을 authorization_code로 설정해야 합니다.
redirect_uri API Console Credentials page 해당 client_id입니다.

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

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 객체를 반환하여 이 요청에 응답합니다. 갱신 토큰이 필요합니다 갱신 토큰은 애플리케이션이 access_type 매개변수를 Google에 보내는 초기 요청에서 offline로 설정합니다. 승인 서버로 이동합니다.

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

필드
access_token 애플리케이션이 Google API 요청을 승인하기 위해 전송하는 토큰입니다.
expires_in 액세스 토큰의 남은 수명(초)입니다.
refresh_token 새 액세스 토큰을 가져오는 데 사용할 수 있는 토큰입니다. 갱신 토큰은 사용자가 액세스를 취소합니다. 앞서 언급했듯이 이 필드는 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 호출

PHP

액세스 토큰을 사용하여 Google API를 호출하려면 다음 단계를 따르세요.

  1. Google\Client 객체에 액세스 토큰을 적용해야 하는 경우 예를 들어 사용자 세션에 액세스 토큰을 저장한 경우 setAccessToken 메서드: <ph type="x-smartling-placeholder">
    $client->setAccessToken($access_token);
    </ph>
  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 요청을 사용할 수 있습니다.

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

Ruby

액세스 토큰을 얻은 후에는 애플리케이션이 해당 토큰을 사용하여 특정 사용자 계정 또는 서비스 계정을 위임할 수 있습니다 사용자별 승인 사용자 인증 정보 사용 호출하려는 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의 서비스 객체를 빌드합니다.

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

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

모든 Google API를 사용해 보고 OAuth 2.0 플레이그라운드.

HTTP GET 예시

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

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 명령줄 애플리케이션을 사용하여 이러한 명령어를 테스트할 수 있습니다. 다음은 예를 들면 다음과 같습니다 (권장).

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 Drive에 있는 파일의 JSON 형식 목록을 사용자가 인증하고 애플리케이션이 사용자의 Drive 메타데이터에 액세스하도록 동의합니다.

PHP

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

  1. API Console에서 로컬 머신의 URL을 리디렉션 URL 목록입니다. 예를 들어 http://localhost:8080를 추가합니다.
  2. 새 디렉터리를 만들어 해당 디렉터리로 변경합니다. 예를 들면 다음과 같습니다.
    mkdir ~/php-oauth2-example
    cd ~/php-oauth2-example
  3. Google API 클라이언트 설치 Composer를 사용하는 PHP용 라이브러리:
    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'])) {
  // Generate and set state value
  $state = bin2hex(random_bytes(16));
  $client->setState($state);
  $_SESSION['state'] = $state;

  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  // Check the state value
  if (!isset($_GET['state']) || $_GET['state'] !== $_SESSION['state']) {
    die('State mismatch. Possible CSRF attack.');
  }
  $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 프레임워크를 사용합니다. 그것은 http://localhost:8080에서 OAuth 2.0을 테스트할 수 있는 웹 애플리케이션을 실행합니다. 있습니다. 해당 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 목록에 추가합니다. 예를 들어 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

기본.js

const http = require('http');
const https = require('https');
const url = require('url');
const { google } = require('googleapis');
const crypto = require('crypto');
const express = require('express');
const session = require('express-session');

/**
 * 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'
];
/* 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 app = express();

  app.use(session({
    secret: 'your_secure_secret_key', // Replace with a strong secret
    resave: false,
    saveUninitialized: false,
  }));

  // Example on redirecting user to Google's OAuth 2.0 server.
  app.get('/', async (req, res) => {
    // Generate a secure random state value.
    const state = crypto.randomBytes(32).toString('hex');
    // Store state in the session
    req.session.state = state;

    // 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,
      // Include the state parameter to reduce the risk of CSRF attacks.
      state: state
    });

    res.redirect(authorizationUrl);
  });

  // Receive the callback from Google's OAuth 2.0 server.
  app.get('/oauth2callback', async (req, res) => {
    // 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 if (q.state !== req.session.state) { //check state value
      console.log('State mismatch. Possible CSRF attack');
      res.end('State mismatch. Possible CSRF attack');
    } 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
  app.get('/revoke', async (req, res) => {
    // 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();
  });


  const server = http.createServer(app);
  server.listen(80);
}
main().catch(console.error);

HTTP/REST

이 Python 예에서는 Flask 프레임워크를 사용합니다. Requests 라이브러리를 사용하여 2.0 웹 흐름. 이 흐름에는 Python용 Google API 클라이언트 라이브러리를 사용하는 것이 좋습니다. ( 는 클라이언트 라이브러리를 사용합니다.)

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:
    state = str(uuid.uuid4())
    flask.session['state'] = state
    auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
                '&client_id={}&redirect_uri={}&scope={}&state={}').format(CLIENT_ID, REDIRECT_URI,
                                                                          SCOPE, state)
    return flask.redirect(auth_uri)
  else:
    if 'state' not in flask.request.args or flask.request.args['state'] != flask.session['state']:
      return 'State mismatch. Possible CSRF attack.', 400

    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는 다음을 포함할 수 없습니다. 열린 리디렉션을 사용하여 Google Cloud Storage에 정보를 저장할 수 있습니다.

    Fragment

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

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

    점진적 승인

    OAuth 2.0 프로토콜에서 앱은 60비트 필드입니다 승인을 요청하는 것이 사용자 환경 권장사항으로 간주됩니다. 리소스를 프로비저닝할 수 있습니다 이를 위해 Google 인증 서버는 단계적 승인을 지원합니다. 이 기능을 사용하면 필요에 따라 범위를 요청할 수 있으며 사용자가 새 범위에 대한 권한을 부여하면 사용자가 프로젝트에 부여한 모든 범위가 포함된 토큰으로 교환합니다.

    예를 들어 음악 트랙을 샘플링하고 믹스를 만들 수 있는 앱에는 리소스, 예를 들면 로그인하는 사람의 이름일 뿐입니다. 하지만 완성된 믹스를 저장하려면 Google Drive에 액세스해야 합니다. 대부분의 사람들은 사용자가 앱을 사용할 때 Google 드라이브에 액세스하라는 요청만 받았다고 해서 필요로 했습니다

    이 경우 로그인 시 앱이 openidprofile 범위를 사용하여 기본 로그인을 수행한 다음 나중에 https://www.googleapis.com/auth/drive.file 범위를 사용하여 혼합해 보겠습니다.

    단계적 승인을 구현하려면 액세스를 요청하는 일반적인 절차를 완료해야 합니다. 토큰이 있어야 하지만 이전에 부여된 범위가 승인 요청에 포함되어 있어야 합니다. 이 이 접근 방식을 사용하면 앱이 여러 개의 액세스 토큰을 관리하지 않아도 됩니다.

    점진적 승인을 통해 얻은 액세스 토큰에는 다음 규칙이 적용됩니다.

    • 이 토큰은 새롭게 통합된 승인입니다.
    • 통합 승인에 대한 갱신 토큰을 사용하여 액세스 토큰을 얻으면 액세스 토큰은 통합 승인을 나타내며 응답에 scope개 값이 포함됩니다.
    • 통합 승인에는 사용자가 API 프로젝트에 부여한 모든 범위가 포함됩니다. 서로 다른 고객으로부터 지원금을 요청한 경우 예를 들어 사용자가 한 범위를 애플리케이션의 데스크톱 클라이언트를 사용하여 지정한 다음 모바일 클라이언트를 통해 애플리케이션을 인증하면 통합 승인에는 두 범위가 모두 포함됩니다.
    • 통합 승인을 나타내는 토큰을 취소하는 경우 해당 토큰 모두에 액세스할 수 있습니다. 동시에 취소됩니다.

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

    PHP

    $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 클라이언트 라이브러리를 사용하는 경우 클라이언트 객체가 새로고침됩니다. 액세스할 수 있도록 객체를 구성해야 합니다.
    • 클라이언트 라이브러리를 사용하지 않는 경우 access_type HTTP를 설정해야 합니다. 쿼리 매개변수를 offline로 리디렉션할 때 Google의 OAuth 2.0 서버. 이 경우 Google 인증 서버는 갱신 토큰 교환 시 코드를 참조하세요. 그런 다음, 액세스 토큰이 만료되는 경우 (또는 다른 시점에) 갱신 토큰을 사용하여 새 액세스 토큰을 받을 수 있습니다.

    오프라인 액세스 요청은 Google 계정에 액세스해야 하는 모든 애플리케이션에 API에 요청을 보낼 수 있습니다. 예를 들어 백업 서비스 또는 백업 복구를 수행하는 앱이 있습니다. 사전에 결정된 시간에 작업을 실행하면 액세스 토큰을 갱신할 수 있어야 사용자가 없습니다. 기본 액세스 스타일은 online입니다.

    서버 측 웹 애플리케이션, 설치된 애플리케이션, 기기가 모두 갱신 토큰을 얻음 승인 프로세스 중에 두 단계를 거치게 됩니다. 갱신 토큰은 일반적으로 클라이언트 측에서 사용되지 않음 (JavaScript) 웹 애플리케이션을 지원합니다.

    PHP

    애플리케이션에서 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_type에서 offline로 메서드를 사용하여 갱신 토큰을 받습니다. 이미 앱에 요청 권한을 부여한 경우 새로고침 토큰을 받기 위해 적절한 제약 조건을 설정하지 않은 경우 새로운 갱신 토큰을 받도록 애플리케이션을 다시 인증합니다.

    나중에 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 요청이 포함될 수 있습니다. 삭제됩니다.

    PHP

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

    $client->revokeToken();

    Python

    토큰을 프로그래매틱 방식으로 취소하려면 https://oauth2.googleapis.com/revoke: 토큰을 매개변수로 포함하고 Content-Type 헤더:

    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가 함께 반환됩니다. 오류 코드가 표시됩니다.