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

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

OAuth 2.0을 사용하면 사용자가 사용자 이름, 비밀번호, 기타 정보를 비공개로 유지하면서 애플리케이션과 특정 데이터를 공유할 수 있습니다. 예를 들어 애플리케이션은 OAuth 2.0을 사용하여 사용자의 YouTube 채널에 동영상을 업로드할 권한을 얻을 수 있습니다.

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

웹 서버 애플리케이션은 특히 Cloud API를 호출하여 사용자별 데이터가 아닌 프로젝트 기반 데이터에 액세스할 때 서비스 계정을 사용하여 API 요청을 승인하는 경우가 많습니다. 웹 서버 애플리케이션은 사용자 승인과 함께 서비스 계정을 사용할 수 있습니다. YouTube Data API는 여러 YouTube 채널을 소유하고 관리하는 YouTube 콘텐츠 소유자에게만 서비스 계정 흐름을 지원합니다. 특히 콘텐츠 소유자는 서비스 계정을 사용하여 onBehalfOfContentOwner 요청 매개변수를 지원하는 API 메서드를 호출할 수 있습니다.

클라이언트 라이브러리

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

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

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

기본 요건

프로젝트에 API 사용 설정

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

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

  1. Google API Console의Open the API Library .
  2. If prompted, select a project, or create a new one.
  3. 보관함 페이지에서 YouTube Data API를 찾아 사용 설정합니다. 애플리케이션에서 사용할 다른 API를 찾아 사용 설정합니다.

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

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의 유효성 검사 규칙을 준수해야 합니다.

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

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

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

액세스 범위 식별

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

OAuth 2.0 승인을 구현하기 전에 앱에서 액세스하는 데 필요한 범위를 식별하는 것이 좋습니다.

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

YouTube Data API v3는 다음 범위를 사용합니다.

범위
https://www.googleapis.com/auth/youtubeYouTube 계정 관리
https://www.googleapis.com/auth/youtube.channel-memberships.creator현재 활동 중인 채널 회원의 목록과 채널 회원의 현재 등급, 회원이 된 시기를 확인할 수 있습니다.
https://www.googleapis.com/auth/youtube.force-ssl내 YouTube 동영상, 평점, 댓글, 캡션의 보기, 수정 및 영구적인 삭제가 가능합니다.
https://www.googleapis.com/auth/youtube.readonlyYouTube 계정 보기
https://www.googleapis.com/auth/youtube.uploadYouTube 동영상 관리
https://www.googleapis.com/auth/youtubepartnerYouTube에서 내 저작물과 관련 콘텐츠 조회 및 관리
https://www.googleapis.com/auth/youtubepartner-channel-auditYouTube 파트너 감사 과정 중 관련된 내 YouTube 채널의 비공개 정보 조회

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

언어별 요구사항

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

2,399필리핀

이 문서의 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 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을 생성하고 해당 URL에 매개변수를 설정합니다.

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

2,399필리핀

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

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

예를 들어 다음 코드는 사용자의 YouTube 계정을 관리하기 위해 오프라인 액세스를 요청합니다.

$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_YOUTUBE::YOUTUBE_FORCE_SSL);

// 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 매개변수를 설정합니다.

예를 들어 다음 코드는 사용자의 YouTube 계정을 관리하기 위해 오프라인 액세스를 요청합니다.

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/youtube.force-ssl'])

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

루비

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

예를 들어 다음 코드는 사용자의 YouTube 계정을 관리하기 위해 오프라인 액세스를 요청합니다.

require 'google/apis/youtube_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/youtube.force-ssl'
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');
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 필수

사용자가 승인 흐름을 완료하면 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에서 사용자에게 표시하는 동의 화면에 알립니다.

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

YouTube Data API v3는 다음 범위를 사용합니다.

범위
https://www.googleapis.com/auth/youtubeYouTube 계정 관리
https://www.googleapis.com/auth/youtube.channel-memberships.creator현재 활동 중인 채널 회원의 목록과 채널 회원의 현재 등급, 회원이 된 시기를 확인할 수 있습니다.
https://www.googleapis.com/auth/youtube.force-ssl내 YouTube 동영상, 평점, 댓글, 캡션의 보기, 수정 및 영구적인 삭제가 가능합니다.
https://www.googleapis.com/auth/youtube.readonlyYouTube 계정 보기
https://www.googleapis.com/auth/youtube.uploadYouTube 동영상 관리
https://www.googleapis.com/auth/youtubepartnerYouTube에서 내 저작물과 관련 콘텐츠 조회 및 관리
https://www.googleapis.com/auth/youtubepartner-channel-auditYouTube 파트너 감사 과정 중 관련된 내 YouTube 채널의 비공개 정보 조회

OAuth 2.0 API 범위 문서에서는 Google API에 액세스하는 데 사용할 수 있는 전체 범위 목록을 제공합니다.

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

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)

루비

  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.redirect(authorizationUrl);

HTTP/REST

Sample redirect to Google's authorization server

The sample URL below requests offline access (access_type=offline) to a scope that permits access to view the user's YouTube account. It uses incremental authorization to ensure that the new access token covers any scopes to which the user previously granted the application access. The URL also sets values for the required redirect_uri, response_type, and client_id parameters as well as for the state parameter. The URL contains line breaks and spaces for readability.

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&
 access_type=offline&
 include_granted_scopes=true&
 state=state_parameter_passthrough_value&
 redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
 response_type=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%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&
 access_type=offline&
 include_granted_scopes=true&
 state=state_parameter_passthrough_value&
 redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
 response_type=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/youtube.force-ssl'],
    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}

루비

콜백 페이지에서 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 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/youtube.force-ssl",
  "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 객체를 제공하여 서비스 객체를 빌드합니다. 예를 들어 YouTube Data API를 호출하려면 다음을 실행합니다.
    $youtube = new Google_Service_YouTube($client);
  3. 서비스 객체가 제공하는 인터페이스를 사용하여 API 서비스에 요청합니다. 예를 들어 승인된 사용자의 YouTube 채널에 대한 데이터를 검색하려면 다음 안내를 따르세요.
    $channel = $youtube->channels->listChannels('snippet', array('mine' => $mine));

Python

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

  1. 호출하려는 API의 서비스 객체를 빌드합니다. API의 이름 및 버전 및 사용자 인증 정보를 사용하여 googleapiclient.discovery 라이브러리의 build 메서드를 호출하여 서비스 객체를 빌드합니다. 예를 들어 다음과 같이 YouTube Data API 버전 3을 호출합니다.
    from googleapiclient.discovery import build
    
    youtube = build('youtube', 'v3', credentials=credentials)
  2. 서비스 객체가 제공하는 인터페이스를 사용하여 API 서비스에 요청합니다. 예를 들어 승인된 사용자의 YouTube 채널에 대한 데이터를 검색하려면 다음 안내를 따르세요.
    channel = youtube.channels().list(mine=True, part='snippet').execute()

루비

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

  1. 호출하려는 API의 서비스 객체를 빌드합니다. 예를 들어 YouTube Data API의 버전 3을 호출하려면 다음을 실행합니다.
    youtube = Google::Apis::YoutubeV3::YouTubeService.new
  2. 서비스의 사용자 인증 정보를 설정합니다.
    youtube.authorization = credentials
  3. 서비스 객체가 제공하는 인터페이스를 사용하여 API 서비스에 요청합니다. 예를 들어 승인된 사용자의 YouTube 채널에 대한 데이터를 검색하려면 다음 안내를 따르세요.
    channel = youtube.list_channels(part, :mine => mine)

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

channel = youtube.list_channels(part, :mine => mine, options: { authorization: auth_client })

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 호출을 설정할 수 있습니다 (예: YouTube Data API를 호출하는 경우).

YouTube Data API는 음반사, 영화 스튜디오 등 여러 YouTube 채널을 소유하고 관리하는 YouTube 콘텐츠 소유자의 서비스 계정만 지원합니다.

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

HTTP GET 예시

Authorization: Bearer HTTP 헤더를 사용하는 youtube.channels 엔드포인트 (YouTube Data API)에 대한 호출은 다음과 같을 수 있습니다. 자체 액세스 토큰을 지정해야 합니다.

GET /youtube/v3/channels?part=snippet&mine=true HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer access_token

다음은 access_token 쿼리 문자열 매개변수를 사용한 인증된 사용자의 동일한 API 호출입니다.

GET https://www.googleapis.com/youtube/v3/channels?access_token=access_token&part=snippet&mine=true

curl

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

curl -H "Authorization: Bearer access_token" https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true

또는 쿼리 문자열 매개변수 옵션을 사용합니다.

curl https://www.googleapis.com/youtube/v3/channels?access_token=access_token&part=snippet&mine=true

전체 예

다음 예에서는 사용자가 애플리케이션에서 사용자의 YouTube 계정을 관리하도록 인증 및 승인한 후 사용자의 YouTube 채널에 대한 정보를 표시하는 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_YOUTUBE::YOUTUBE_FORCE_SSL);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
  $youtube = new Google_Service_YouTube($client);
  $channel = $youtube->channels->listChannels('snippet', array('mine' => $mine));
  echo json_encode($channel);
} 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_YOUTUBE::YOUTUBE_FORCE_SSL);

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/youtube.force-ssl']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'

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

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

  channel = youtube.channels().list(mine=True, part='snippet').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(**channel)


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

루비

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

require 'google/apis/youtube_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
  youtube = Google::Apis::YoutubeV3::YouTubeService.new
  channel = youtube.list_channels(part, :mine => mine, options: { authorization: auth_client })
  
  "<pre>#{JSON.pretty_generate(channel.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');
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 라이브러리를 사용해 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/youtube.force-ssl'
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/youtube/v3/channels/list'
    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는 열린 리디렉션을 포함할 수 없습니다.

    Fragment

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

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

    점진적 승인

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

    예를 들어 관심 있는 지역 이벤트를 파악하는 데 도움이 되는 앱이 있다고 가정해 보겠습니다. 이 앱을 통해 사용자는 이벤트에 대한 동영상을 보고, 동영상을 평가하고, 재생목록에 동영상을 추가할 수 있습니다. 사용자는 이 앱을 사용하여 Google 캘린더에 이벤트를 추가할 수도 있습니다.

    이 경우 로그인 시 앱이 어떠한 범위에 대한 액세스도 필요하지 않거나 요청할 필요가 없습니다. 그러나 사용자가 동영상을 평가하거나 재생목록에 동영상을 추가하거나 다른 YouTube 작업을 실행하려고 하면 앱이 https://www.googleapis.com/auth/youtube.force-ssl 범위에 대한 액세스를 요청할 수 있습니다. 마찬가지로 사용자가 캘린더 이벤트를 추가하려고 하면 앱이 https://www.googleapis.com/auth/calendar 범위에 대한 액세스를 요청할 수 있습니다.

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

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

    • 토큰을 사용하여 새로운 결합된 승인에 롤백된 범위에 해당하는 리소스에 액세스할 수 있습니다.
    • 결합된 승인에 갱신 토큰을 사용하여 액세스 토큰을 얻는 경우 액세스 토큰은 결합된 승인을 나타내며 응답에 포함된 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')

    루비

    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

    이 예에서 호출하는 애플리케이션은 사용자가 이미 애플리케이션에 부여한 다른 액세스 권한 외에 사용자의 YouTube 분석 데이터를 검색할 수 있는 액세스 권한을 요청합니다.

    GET https://accounts.google.com/o/oauth2/v2/auth?
      scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyt-analytics.readonly&
      access_type=offline&
      state=security_token%3D138rk%3Btarget_url%3Dhttp...index&
      redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
      response_type=code&
      client_id=client_id&
      include_granted_scopes=true
    
          

    Refreshing an access token (offline access)

    Access tokens periodically expire and become invalid credentials for a related API request. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.

    • If you use a Google API Client Library, the client object refreshes the access token as needed as long as you configure that object for offline access.
    • If you are not using a client library, you need to set the access_type HTTP query parameter to offline when redirecting the user to Google's OAuth 2.0 server. In that case, Google's authorization server returns a refresh token when you exchange an authorization code for an access token. Then, if the access token expires (or at any other time), you can use a refresh token to obtain a new access token.

    Requesting offline access is a requirement for any application that needs to access a Google API when the user is not present. For example, an app that performs backup services or executes actions at predetermined times needs to be able to refresh its access token when the user is not present. The default style of access is called online.

    Server-side web applications, installed applications, and devices all obtain refresh tokens during the authorization process. Refresh tokens are not typically used in client-side (JavaScript) web applications.

    PHP

    If your application needs offline access to a Google API, set the API client's access type to 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에 액세스할 수 있습니다. 클라이언트 객체는 필요에 따라 액세스 토큰을 새로고침합니다.

    루비

    애플리케이션에서 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"
    }

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

    토큰 취소

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

    또한 애플리케이션에서 프로그래밍 방식으로 주어진 액세스 권한을 취소할 수도 있습니다. 프로그래매틱 취소는 사용자가 구독을 취소하거나 애플리케이션을 삭제하거나 앱에 필요한 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'})

    루비

    프로그래매틱 방식으로 토큰을 취소하려면 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가 오류 코드와 함께 반환됩니다.