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 서버 구현

승인 코드 흐름의 OAuth 2.0 서버 구현은 서비스에서 HTTPS를 통해 제공하는 두 개의 엔드포인트로 구성됩니다. 첫 번째 엔드포인트는 데이터 액세스에 대한 사용자 동의를 찾거나 획득하는 역할을 하는 승인 엔드포인트입니다. 승인 엔드포인트는 아직 로그인하지 않은 사용자에게 로그인 UI를 표시하고 요청된 액세스에 대한 동의를 기록합니다. 두 번째 엔드포인트는 토큰 교환 엔드포인트로, 사용자가 서비스에 액세스할 수 있도록 승인하는 토큰이라는 암호화된 문자열을 획득하는 데 사용됩니다.

Google 애플리케이션이 서비스의 API 중 하나를 호출해야 하는 경우 Google은 이러한 엔드포인트를 함께 사용하여 사용자를 대신하여 이러한 API를 호출할 권한을 사용자로부터 얻습니다.

Google 계정 연결: OAuth 승인 코드 플로우

다음 시퀀스 다이어그램은 사용자, Google, 서비스의 엔드포인트 간의 상호작용을 자세히 설명합니다.

사용자 Google 앱 / 브라우저 Google 서버 인증 엔드포인트 토큰 엔드포인트 1. 사용자가 연결을 시작합니다. 2. 인증 엔드포인트로 리디렉션 (GET) client_id, redirect_uri, state, scope 3. 로그인 및 동의 화면 표시 4. 사용자 인증 및 동의 부여 5. Google로 다시 리디렉션 (GET) code, state 6. 리디렉션 처리 및 코드/상태 전달 7. 토큰 교환 (POST) grant_type=authorization_code, code 8. 토큰 반환 (200 OK) access_token, refresh_token 9. 사용자 토큰 저장 10. 사용자 리소스 액세스
그림 1. Google 계정 연결을 위한 OAuth 2.0 승인 코드 플로우의 이벤트 시퀀스입니다.

역할 및 책임

다음 표에서는 Google 계정 연결 (GAL) OAuth 흐름의 행위자의 역할과 책임을 정의합니다. GAL에서 Google은 OAuth 클라이언트 역할을 하고 서비스는 ID/서비스 제공업체 역할을 합니다.

작업 수행자 / 구성요소 GAL 역할 책임
Google 앱 / 서버 OAuth 클라이언트 흐름을 시작하고, 승인 코드를 수신하고, 토큰으로 교환하고, 서비스의 API에 액세스하기 위해 안전하게 저장합니다.
승인 엔드포인트 승인 서버 사용자를 인증하고 Google과 데이터 액세스 권한을 공유하는 데 대한 사용자의 동의를 얻습니다.
토큰 교환 엔드포인트 승인 서버 승인 코드와 갱신 토큰을 검증하고 Google 서버에 액세스 토큰을 발급합니다.
Google 리디렉션 URI 콜백 엔드포인트 codestate 값이 포함된 승인 서비스에서 사용자 리디렉션을 수신합니다.

Google에서 시작한 OAuth 2.0 승인 코드 플로우 세션은 다음과 같은 플로우를 갖습니다.

  1. Google이 사용자의 브라우저에서 승인 엔드포인트를 엽니다. 작업의 흐름이 음성 전용 기기에서 시작된 경우 Google은 실행을 휴대전화로 트랜스퍼합니다.
  2. 사용자가 아직 로그인하지 않은 경우 로그인하고, 아직 권한을 부여하지 않은 경우 Google에 API로 데이터에 액세스할 수 있는 권한을 부여합니다.
  3. 서비스가 승인 코드를 만들어 Google에 반환합니다. 이렇게 하려면 요청에 승인 코드를 첨부하여 사용자의 브라우저를 Google로 다시 리디렉션하세요.
  4. Google은 승인 코드를 토큰 교환 엔드포인트로 전송하며, 이 엔드포인트는 코드의 진위성을 확인하고 액세스 토큰갱신 토큰을 반환합니다. 액세스 토큰은 서비스가 API에 액세스하기 위한 사용자 인증 정보로 허용하는 단기 토큰입니다. 갱신 토큰은 Google이 저장하고 액세스 토큰이 만료될 때 새 액세스 토큰을 획득하는 데 사용할 수 있는 장기 토큰입니다.
  5. 사용자가 계정 연결 흐름을 완료한 후 Google에서 전송되는 모든 후속 요청에는 액세스 토큰이 포함됩니다.

구현 레시피

다음 단계에 따라 승인 코드 플로우를 구현하세요.

1단계: 승인 요청 처리

Google이 계정 연결을 시작하면 사용자를 승인 엔드포인트로 리디렉션합니다. 자세한 프로토콜 계약 및 매개변수 요구사항은 인증 엔드포인트를 참고하세요.

요청을 처리하려면 다음 작업을 실행하세요.

  1. 요청 유효성 검사:

    • client_id이 Google에 할당된 클라이언트 ID와 일치하는지 확인합니다.
    • redirect_uri이 예상되는 Google 리디렉션 URL과 일치하는지 확인합니다. none https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID https://oauth-redirect-sandbox.googleusercontent.com/r/YOUR_PROJECT_ID
    • response_typecode인지 확인합니다.
  2. 사용자 인증:

    • 사용자가 서비스에 로그인했는지 확인합니다.
    • 사용자가 로그인하지 않은 경우 로그인 또는 가입 절차를 완료하라는 메시지를 표시합니다.
  3. 승인 코드 생성:

    • 사용자 및 클라이언트와 연결된 추측할 수 없는 고유한 승인 코드를 만듭니다.
    • 코드가 약 10분 후에 만료되도록 설정합니다.
  4. Google로 다시 리디렉션:

    • 브라우저를 redirect_uri에 제공된 URL로 리디렉션합니다.
    • 다음 쿼리 매개변수를 추가합니다.
      • code: 생성한 승인 코드입니다.
      • state: Google에서 수신한 수정되지 않은 상태 값입니다.

2단계: 토큰 교환 요청 처리

토큰 교환 엔드포인트는 토큰용 코드 교환과 만료된 액세스 토큰 새로고침이라는 두 가지 유형의 요청을 처리합니다. 자세한 프로토콜 계약 및 매개변수 요구사항은 토큰 교환 엔드포인트를 참고하세요.

A. 승인 코드를 토큰으로 교환

Google에서 승인 코드를 수신하면 토큰 교환 엔드포인트 (POST)를 호출하여 토큰을 가져옵니다.

  1. 요청 유효성 검사:

    • client_idclient_secret을 확인합니다.
    • 승인 코드가 유효하고 만료되지 않았는지 확인합니다.
    • redirect_uri이 1단계에서 사용한 값과 일치하는지 확인합니다.
    • 유효성 검사가 실패하면 {"error": "invalid_grant"}와 함께 HTTP 400 Bad Request를 반환합니다.
  2. 토큰 발급:

    • 장기 refresh_token와 단기 access_token (일반적으로 1시간)을 생성합니다.
    • 표준 JSON 토큰 응답과 함께 HTTP 200 OK를 반환합니다.

B. 액세스 토큰 새로고침

액세스 토큰이 만료되면 Google은 갱신 토큰을 사용하여 새 토큰을 요청합니다.

  1. 요청 유효성 검사:

    • client_id, client_secret, refresh_token를 확인합니다.
    • 유효성 검사가 실패하면 {"error": "invalid_grant"}와 함께 HTTP 400 Bad Request를 반환합니다.
  2. 새 액세스 토큰 발급:

    • 새 단기 access_token를 생성합니다.
    • JSON 토큰 응답 (선택적으로 새 갱신 토큰 포함)과 함께 HTTP 200 OK를 반환합니다.
Handle userinfo requests

The userinfo endpoint is an OAuth 2.0 protected resource that return claims about the linked user. Implementing and hosting the userinfo endpoint is optional, except for the following use cases:

After the access token has been successfully retrieved from your token endpoint, Google sends a request to your userinfo endpoint to retrieve basic profile information about the linked user.

userinfo endpoint request headers
Authorization header The access token of type Bearer.

For example, if your userinfo endpoint is available at https://myservice.example.com/userinfo, a request might look like the following:

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

For your userinfo endpoint to handle requests, do the following steps:

  1. Extract access token from the Authorization header and return information for the user associated with the access token.
  2. If the access token is invalid, return an HTTP 401 Unauthorized error with using the WWW-Authenticate Response Header. Below is an example of a userinfo error response:
    HTTP/1.1 401 Unauthorized
    WWW-Authenticate: error="invalid_token",
    error_description="The Access Token expired"
    
    If a 401 Unauthorized, or any other unsuccessful error response is returned during the linking process, the error will be non-recoverable, the retrieved token will be discarded and the user will have to initiate the linking process again.
  3. If the access token is valid, return and HTTP 200 response with the following JSON object in the body of the HTTPS response:

    {
    "sub": "USER_UUID",
    "email": "EMAIL_ADDRESS",
    "given_name": "FIRST_NAME",
    "family_name": "LAST_NAME",
    "name": "FULL_NAME",
    "picture": "PROFILE_PICTURE",
    }
    If your userinfo endpoint returns an HTTP 200 success response, the retrieved token and claims are registered against the user's Google account.

    userinfo endpoint response
    sub A unique ID that identifies the user in your system.
    email Email address of the user.
    given_name Optional: First name of the user.
    family_name Optional: Last name of the user.
    name Optional: Full name of the user.
    picture Optional: Profile picture of the user.

구현 확인

You can validate your implementation by using the OAuth 2.0 Playground tool.

In the tool, do the following steps:

  1. Click Configuration to open the OAuth 2.0 Configuration window.
  2. In the OAuth flow field, select Client-side.
  3. In the OAuth Endpoints field, select Custom.
  4. Specify your OAuth 2.0 endpoint and the client ID you assigned to Google in the corresponding fields.
  5. In the Step 1 section, don't select any Google scopes. Instead, leave this field blank or type a scope valid for your server (or an arbitrary string if you don't use OAuth scopes). When you're done, click Authorize APIs.
  6. In the Step 2 and Step 3 sections, go through the OAuth 2.0 flow and verify that each step works as intended.

You can validate your implementation by using the Google Account Linking Demo tool.

In the tool, do the following steps:

  1. Click the Sign in with Google button.
  2. Choose the account you'd like to link.
  3. Enter the service ID.
  4. Optionally enter one or more scopes that you will request access for.
  5. Click Start Demo.
  6. When prompted, confirm that you may consent and deny the linking request.
  7. Confirm that you are redirected to your platform.