OAuth로 Google 계정 연결

계정은 업계 표준 OAuth 2.0 승인 코드 흐름을 사용하여 연결됩니다.

에이전트용 OAuth 2.1 및 PKCE

상태 비저장 AI 에이전트 및 멀티모달 파이프라인의 경우 OAuth 2.1 시행이 권장됩니다.

  • PKCE (Proof Key for Code Exchange): 승인 코드 플로우를 보호하고 가로채기 공격을 방지하는 데 사용해야 합니다.
  • 암시적 흐름 없음: 암시적 흐름은 URL에 액세스 토큰을 노출하므로 에이전트 환경에 보안 위험이 됩니다.

서비스는 OAuth 2.0/2.1 호환 승인토큰 교환 엔드포인트를 지원해야 합니다.

Create the project

To create your project to use account linking:

  1. Go to the Google API Console.
  2. Click Create project.
  3. Enter a name or accept the generated suggestion.
  4. Confirm or edit any remaining fields.
  5. Click Create.

To view your project ID:

  1. Go to the Google API Console.
  2. Find your project in the table on the landing page. The project ID appears in the ID column.

The Google Account Linking process includes a consent screen which tells users the application requesting access to their data, what kind of data they are asking for and the terms that apply. You will need to configure your OAuth consent screen before generating a Google API client ID.

  1. Open the OAuth consent screen page of the Google APIs console.
  2. If prompted, select the project you just created.
  3. On the "OAuth consent screen" page, fill out the form and click the “Save” button.

    Application name: The name of the application asking for consent. The name should accurately reflect your application and be consistent with the application name users see elsewhere. The application name will be shown on the Account Linking consent screen.

    Application logo: An image on the consent screen that will help users recognize your app. The logo is shown on Account linking consent screen and on account settings

    Support email: For users to contact you with questions about their consent.

    Scopes for Google APIs: Scopes allow your application to access your user's private Google data. For the Google Account Linking use case, default scope (email, profile, openid) is sufficient, you don’t need to add any sensitive scopes. It is generally a best practice to request scopes incrementally, at the time access is required, rather than up front. Learn more.

    Authorized domains: To protect you and your users, Google only allows applications that authenticate using OAuth to use Authorized Domains. Your applications' links must be hosted on Authorized Domains. Learn more.

    Application Homepage link: Home page for your application. Must be hosted on an Authorized Domain.

    Application Privacy Policy link: Shown on Google Account Linking consent screen. Must be hosted on an Authorized Domain.

    Application Terms of Service link (Optional): Must be hosted on an Authorized Domain.

    Figure 1. Google Account Linking Consent Screen for a fictitious Application, Tunery

  4. Check "Verification Status", if your application needs verification then click the "Submit For Verification" button to submit your application for verification. Refer to OAuth verification requirements for details.

OAuth 서버 구현

An OAuth 2.0 server implementation of the authorization code flow consists of two endpoints, which your service makes available by HTTPS. The first endpoint is the authorization endpoint, which is responsible for finding or obtaining consent from users for data access. The authorization endpoint presents a sign-in UI to your users that aren't already signed in and records consent to the requested access. The second endpoint is the token exchange endpoint, which is used to obtain encrypted strings, called tokens, that authorize a user to access your service.

When a Google application needs to call one of your service's APIs, Google uses these endpoints together to get permission from your users to call these APIs on their behalf.

Google Account Linking: OAuth Authorization Code Flow

The following sequence diagram details interactions between the User, Google, and your service's endpoints.

User Google App / Browser Google Server Your Auth Endpoint Your Token Endpoint 1. User initiates linking 2. Redirect to Auth Endpoint (GET) client_id, redirect_uri, state, scope 3. Display Sign-in & Consent Screen 4. User Authenticates & Grants Consent 5. Redirect back to Google (GET) code, state 6. Handle redirect & pass code/state 7. Token Exchange (POST) grant_type=authorization_code, code 8. Return Tokens (200 OK) access_token, refresh_token 9. Store user tokens 10. Access user resources
Figure 1. The sequence of events in the OAuth 2.0 Authorization Code flow for Google Account Linking.

Roles and responsibilities

The following table defines the roles and responsibilities of the actors in the Google Account Linking (GAL) OAuth flow. Note that in GAL, Google acts as the OAuth Client, while your service acts as the Identity/Service Provider.

Actor / Component GAL Role Responsibilities
Google App / Server OAuth Client Initiates the flow, receives the authorization code, exchanges it for tokens, and securely stores them to access your service's APIs.
Your Authorization Endpoint Authorization Server Authenticates your users and obtains their consent to share access to their data with Google.
Your Token Exchange Endpoint Authorization Server Validates authorization codes and refresh tokens, and issues access tokens to the Google Server.
Google Redirect URI Callback Endpoint Receives the user redirect from your authorization service with the code and state values.

An OAuth 2.0 authorization code flow session initiated by Google has the following flow:

  1. Google opens your authorization endpoint in the user's browser. If the flow started on a voice-only device for an Action, Google transfers the execution to a phone.
  2. The user signs in, if not signed in already, and grants Google permission to access their data with your API, if they haven't already granted permission.
  3. Your service creates an authorization code and returns it to Google. To do so, redirect the user's browser back to Google with the authorization code attached to the request.
  4. Google sends the authorization code to your token exchange endpoint, which verifies the authenticity of the code and returns an access token and a refresh token. The access token is a short-lived token that your service accepts as credentials to access APIs. The refresh token is a long-lived token that Google can store and use to acquire new access tokens when they expire.
  5. After the user has completed the account linking flow, every subsequent request sent from Google contains an access token.

Implementation Recipe

Follow these steps to implement the Authorization Code flow.

Step 1: Handle authorization requests

When Google initiates account linking, it redirects the user to your authorization endpoint. For detailed protocol contracts and parameter requirements, see the Authorization Endpoint.

To handle the request, perform the following actions:

  1. Validate the request:

    • Confirm that the client_id matches the Client ID assigned to Google.
    • Confirm that the redirect_uri matches the expected Google redirect URL: none https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID https://oauth-redirect-sandbox.googleusercontent.com/r/YOUR_PROJECT_ID
    • Verify that response_type is code.
  2. Authenticate the user:

    • Check if the user is signed in to your service.
    • If the user is not signed in, prompt them to complete your sign-in or sign-up flow.
  3. Generate authorization code:

    • Create a unique, non-guessable authorization code associated with the user and client.
    • Set the code to expire in approximately 10 minutes.
  4. Redirect back to Google:

    • Redirect the browser to the URL provided in redirect_uri.
    • Append the following query parameters:
      • code: The authorization code you generated.
      • state: The unmodified state value received from Google.

Step 2: Handle token exchange requests

Your token exchange endpoint processes two types of requests: exchanging codes for tokens, and refreshing expired access tokens. For detailed protocol contracts and parameter requirements, see the Token Exchange Endpoint.

A. Exchange authorization codes for tokens

When Google receives the authorization code, it calls your token exchange endpoint (POST) to retrieve tokens.

  1. Validate the request:

    • Verify client_id and client_secret.
    • Verify the authorization code is valid and not expired.
    • Confirm redirect_uri matches the value used in Step 1.
    • If validation fails, return an HTTP 400 Bad Request with {"error": "invalid_grant"}.
  2. Issue tokens:

    • Generate a long-lived refresh_token and a short-lived access_token (typically 1 hour).
    • Return an HTTP 200 OK with the standard JSON token response.

B. Refresh access tokens

When the access token expires, Google requests a new one using the refresh token.

  1. Validate the request:

    • Verify client_id, client_secret, and refresh_token.
    • If validation fails, return an HTTP 400 Bad Request with {"error": "invalid_grant"}.
  2. Issue new access token:

    • Generate a new short-lived access_token.
    • Return an HTTP 200 OK with the JSON token response (optionally including a new refresh token).
사용자 정보 요청 처리

userinfo 엔드포인트는 연결된 사용자에 대한 클레임을 반환하는 OAuth 2.0 보호 리소스입니다. 다음 사용 사례를 제외하고 userinfo 엔드포인트를 구현하고 호스팅하는 것은 선택사항입니다.

토큰 엔드포인트에서 액세스 토큰을 성공적으로 가져오면 Google은 사용자 정보 엔드포인트에 요청을 보내 연결된 사용자에 대한 기본 프로필 정보를 가져옵니다.

사용자 정보 엔드포인트 요청 헤더
Authorization header Bearer 유형의 액세스 토큰입니다.

예를 들어 https://myservice.example.com/userinfo인 경우 요청은 다음과 같을 수 있습니다.

GET /userinfo HTTP/1.1
Host: myservice.example.com
Authorization: Bearer ACCESS_TOKEN

userinfo 엔드포인트에서 요청을 처리하려면 다음 단계를 수행합니다.

  1. 승인 헤더에서 액세스 토큰을 추출하고 액세스 토큰과 연결된 사용자의 정보를 반환합니다.
  2. 액세스 토큰이 유효하지 않은 경우 WWW-Authenticate 응답 헤더를 사용하여 HTTP 401 승인되지 않은 오류를 반환합니다. 다음은 userinfo 오류 응답의 예입니다.
    HTTP/1.1 401 Unauthorized
    WWW-Authenticate: error="invalid_token",
    error_description="The Access Token expired"
    
    드림 연결 과정 중에 401 승인되지 않음 또는 기타 실패한 오류 응답이 반환되면 오류는 복구할 수 없으며 검색된 토큰은 삭제되며 사용자는 연결 프로세스를 다시 시작해야 합니다.
  3. 액세스 토큰이 유효하면 HTTPS 본문에 다음 JSON 객체가 포함된 HTTP 200 응답을 반환합니다. 응답:

    {
    "sub": "USER_UUID",
    "email": "EMAIL_ADDRESS",
    "given_name": "FIRST_NAME",
    "family_name": "LAST_NAME",
    "name": "FULL_NAME",
    "picture": "PROFILE_PICTURE",
    }
    드림 userinfo 엔드포인트가 HTTP 200 성공 응답을 반환하는 경우 가져온 토큰과 클레임은 사용자의 Google 계정에 등록됩니다.

    사용자 정보 엔드포인트 응답
    sub 시스템에서 사용자를 식별하는 고유 ID
    email 사용자의 이메일 주소입니다.
    given_name 선택사항: 사용자의 이름입니다.
    family_name 선택사항: 사용자의 성.
    name 선택사항: 사용자의 전체 이름입니다.
    picture 선택사항: 사용자의 프로필 사진입니다.

구현 확인

OAuth 2.0 Playground 도구를 사용하여 구현의 유효성을 검사할 수 있습니다.

도구에서 다음 단계를 수행합니다.

  1. 구성 을 클릭하여 OAuth 2.0 구성 창을 엽니다.
  2. OAuth 흐름 필드에서 클라이언트 측 을 선택합니다.
  3. OAuth 엔드포인트 필드에서 맞춤 을 선택합니다.
  4. 해당 필드에서 OAuth 2.0 엔드포인트와 Google에 할당한 클라이언트 ID를 지정합니다.
  5. 1단계 섹션에서 Google 범위를 선택하지 않습니다. 대신 이 필드를 비워 두거나 서버에 유효한 범위 (또는 OAuth 범위를 사용하지 않는 경우 임의의 문자열)를 입력합니다. 완료되면 API 승인 을 클릭합니다.
  6. 2단계3단계 섹션에서 OAuth 2.0 흐름을 진행하고 각 단계가 의도한 대로 작동하는지 확인합니다.

Google 계정 연결 데모 도구를 사용하여 구현의 유효성을 검사할 수 있습니다.

도구에서 다음 단계를 수행합니다.

  1. Google 계정으로 로그인 버튼을 클릭합니다.
  2. 연결하려는 계정을 선택합니다.
  3. 서비스 ID를 입력합니다.
  4. 액세스 권한을 요청할 범위를 하나 이상 입력합니다(선택사항).
  5. 데모 시작 을 클릭합니다.
  6. 메시지가 표시되면 연결 요청에 동의하거나 거부할 수 있음을 확인합니다.
  7. 플랫폼으로 리디렉션되는지 확인합니다.