OAuth를 사용한 계정 연결

OAuth 연결 유형은 두 가지 업계 표준 OAuth 2.0 흐름, 즉 암시적승인 코드 흐름을 지원합니다.

암시적 코드 흐름에서 Google은 사용자의 브라우저에서 승인 엔드포인트를 엽니다. 로그인에 성공하면 수명이 긴 액세스 토큰을 Google에 반환합니다. 이제 어시스턴트에서 작업으로 전송되는 모든 요청에 이 액세스 토큰이 포함됩니다.

승인 코드 흐름에는 두 개의 엔드포인트가 필요합니다.

  • 승인 엔드포인트: 아직 로그인하지 않은 사용자에게 로그인 UI를 표시하고 요청한 액세스에 대한 동의를 단기 승인 코드 형식으로 기록하는 역할을 합니다.
  • 두 가지 유형의 교환을 담당하는 토큰 교환 엔드포인트:
    1. 장기 갱신 토큰과 단기 액세스 토큰으로 승인 코드를 교환합니다. 이 교환은 사용자가 계정 연결 흐름을 진행할 때 이루어집니다.
    2. 장기 갱신 토큰을 단기 액세스 토큰으로 교환합니다. 이 교환은 액세스 토큰이 만료되어 Google에 새 액세스 토큰이 필요할 때 발생합니다.

암시적 코드 흐름을 구현하는 것이 더 간단하지만 암시적 흐름을 사용하여 발급된 액세스 토큰은 만료되지 않는 것이 좋습니다. 토큰 만료를 암시적 흐름과 함께 사용하면 사용자가 계정을 다시 연결하게 되기 때문입니다. 보안상의 이유로 토큰 만료가 필요하다면 인증 코드 흐름을 대신 사용하는 것이 좋습니다.

OAuth 계정 연결 구현

프로젝트 구성

OAuth 연결을 사용하도록 프로젝트를 구성하려면 다음 단계를 따르세요.

  1. Actions Console을 열고 사용할 프로젝트를 선택합니다.
  2. 개발 탭을 클릭하고 계정 연결을 선택합니다.
  3. 계정 연결 옆에 있는 스위치를 사용 설정합니다.
  4. 계정 생성 섹션에서 아니요, 내 웹사이트에서만 계정 생성을 허용하고 싶습니다를 선택합니다.
  5. 연결 유형에서 OAuth승인 코드를 선택합니다.

  6. 클라이언트 정보:

    • Actions에서 Google에 발행한 클라이언트 ID에 값을 할당하여 Google에서 수신되는 요청을 식별합니다.
    • Google에서 작업에 발급한 클라이언트 ID의 값을 기록해 둡니다.
    • 승인 및 토큰 교환 엔드포인트의 URL을 삽입합니다.
  1. 저장을 클릭합니다.

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 the Action user to access your service.

When your Action 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.

OAuth 2.0 auth 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 would transfer 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 by redirecting 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 the Assistant to your fulfillment webhook contains an access token.

Handle authorization requests

When your Action needs to perform account linking via an OAuth 2.0 authorization code flow, Google sends the user to your authorization endpoint with a request that includes the following parameters:

Authorization endpoint parameters
client_id The Google client ID you registered with Google.
redirect_uri The URL to which you send the response to this request.
state A bookkeeping value that is passed back to Google unchanged in the redirect URI.
scope Optional: A space-delimited set of scope strings that specify the data Google is requesting authorization for.
response_type The string code.

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

GET https://myservice.example.com/auth?client_id=GOOGLE_CLIENT_ID&redirect_uri=REDIRECT_URI&state=STATE_STRING&scope=REQUESTED_SCOPES&response_type=code

For your authorization endpoint to handle sign-in requests, do the following steps:

  1. Verify that the client_id matches the Google client ID you registered with Google, and that the redirect_uri matches the redirect URL provided by Google for your service. These checks are important to prevent granting access to unintended or misconfigured client apps.

    If you support multiple OAuth 2.0 flows, also confirm that the response_type is code.

  2. Check if the user is signed in to your service. If the user isn't signed in, complete your service's sign-in or sign-up flow.

  3. Generate an authorization code that Google will use to access your API. The authorization code can be any string value, but it must uniquely represent the user, the client the token is for, and the code's expiration time, and it must not be guessable. You typically issue authorization codes that expire after approximately 10 minutes.

  4. Confirm that the URL specified by the redirect_uri parameter has the following form:

    https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID
    YOUR_PROJECT_ID is the ID found on the Project settings page of the Actions Console.

  5. Redirect the user's browser to the URL specified by the redirect_uri parameter. Include the authorization code you just generated and the original, unmodified state value when you redirect by appending the code and state parameters. The following is an example of the resulting URL:

    https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID?code=AUTHORIZATION_CODE&state=STATE_STRING

Handle token exchange requests

Your service's token exchange endpoint is responsible for two kinds of token exchanges:

  • Exchange authorization codes for access tokens and refresh tokens
  • Exchange refresh tokens for access tokens

Token exchange requests include the following parameters:

Token exchange endpoint parameters
client_id A string that identifies the request origin as Google. This string must be registered within your system as Google's unique identifier.
client_secret A secret string that you registered with Google for your service.
grant_type The type of token being exchanged. Either authorization_code or refresh_token.
code When grant_type=authorization_code, the code Google received from either your sign-in or token exchange endpoint.
redirect_uri When grant_type=authorization_code, this parameter is the URL used in the initial authorization request.
refresh_token When grant_type=refresh_token, the refresh token Google received from your token exchange endpoint.
Exchange authorization codes for access tokens and refresh tokens

After the user signs in and your authorization endpoint returns a short-lived authorization code to Google, Google sends a request to your token exchange endpoint to exchange the authorization code for an access token and a refresh token.

For these requests, the value of grant_type is authorization_code, and the value of code is the value of the authorization code you previously granted to Google. The following is an example of a request to exchange an authorization code for an access token and a refresh token:

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

client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET&grant_type=authorization_code&code=AUTHORIZATION_CODE&redirect_uri=REDIRECT_URI

To exchange authorization codes for an access token and a refresh token, your token exchange endpoint responds to POST requests executing the following steps:

  1. Verify that the client_id identifies the request origin as an authorized origin, and that the client_secret matches the expected value.
  2. Verify the following:
    • The authorization code is valid and not expired, and the client ID specified in the request matches the client ID associated with the authorization code.
    • The URL specified by the redirect_uri parameter is identical to the value used in the initial authorization request.
  3. If you cannot verify all of the above criteria, return an HTTP 400 Bad Request error with {"error": "invalid_grant"} as the body.
  4. Otherwise, using the user ID from the authorization code, generate a refresh token and an access token. These tokens can be any string value, but they must uniquely represent the user and the client the token is for, and they must not be guessable. For access tokens, also record the expiration time of the token (typically an hour after you issue the token). Refresh tokens do not expire.
  5. Return the following JSON object in the body of the HTTPS response:
    {
    "token_type": "Bearer",
    "access_token": "ACCESS_TOKEN",
    "refresh_token": "REFRESH_TOKEN",
    "expires_in": SECONDS_TO_EXPIRATION
    }
    

Google stores the access token and the refresh token for the user and records the expiration of the access token. When the access token expires, Google uses the refresh token to get a new access token from your token exchange endpoint.

Exchange refresh tokens for access tokens

When an access token expires, Google sends a request to your token exchange endpoint to exchange a refresh token for a new access token.

For these requests, the value of grant_type is refresh_token, and the value of refresh_token is the value of the refresh token you previously granted to Google. The following is an example of a request to exchange a refresh token for an access token:

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

client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

To exchange a refresh token for an access token, your token exchange endpoint responds to POST requests executing the following steps:

  1. Verify that the client_id identifies the request origin as Google, and that the client_secret matches the expected value.
  2. Verify that the refresh token is valid, and that the client ID specified in the request matches the client ID associated with the refresh token.
  3. If you cannot verify all of the above criteria, return an HTTP 400 Bad Request error with {"error": "invalid_grant"} as the body.
  4. Otherwise, use the user ID from the refresh token to generate an access token. These tokens can be any string value, but they must uniquely represent the user and the client the token is for, and they must not be guessable. For access tokens, also record the expiration time of the token (typically an hour after you issue the token).
  5. Return the following JSON object in the body of the HTTPS response:
    {
    "token_type": "Bearer",
    "access_token": "ACCESS_TOKEN",
    "expires_in": SECONDS_TO_EXPIRATION
    }

인증 흐름을 위한 음성 사용자 인터페이스 설계

사용자가 인증되었는지 확인하고 계정 연결 흐름을 시작합니다.

  1. Actions 콘솔에서 Actions Builder 프로젝트를 엽니다.
  2. 작업에서 계정 연결을 시작할 새 장면을 만듭니다.
    1. 장면을 클릭합니다.
    2. add (+) 아이콘을 클릭하여 새 장면을 추가합니다.
  3. 새로 만든 장면에서 조건의 추가 아이콘을 클릭합니다.
  4. 대화와 연결된 사용자가 인증된 사용자인지 확인하는 조건을 추가합니다. 검사에 실패하면 작업이 대화 중에 계정 연결을 실행할 수 없으며 계정 연결이 필요하지 않은 기능에 대한 액세스 권한을 제공하는 것으로 대체됩니다.
    1. 조건Enter new expression 필드에 다음 로직을 입력합니다. user.verificationStatus != "VERIFIED"
    2. Transition에서 계정 연결이 필요하지 않은 장면이나 게스트 전용 기능의 진입점인 장면을 선택합니다.

  1. 조건의 추가 아이콘을 클릭합니다.
  2. 사용자에게 연결된 ID가 없는 경우 계정 연결 흐름을 트리거하는 조건을 추가합니다.
    1. 조건Enter new expression 필드에 다음 로직을 입력합니다. user.verificationStatus == "VERIFIED"
    2. Transition에서 Account Linking 시스템 장면을 선택합니다.
    3. 저장을 클릭합니다.

저장하면 <SceneName>_AccountLinking라는 새 계정 연결 시스템 장면이 프로젝트에 추가됩니다.

계정 연결 장면 맞춤설정

  1. Scenes(장면)에서 계정 연결 시스템 장면을 선택합니다.
  2. 메시지 보내기를 클릭하고 작업에서 사용자 ID에 액세스해야 하는 이유를 설명하는 짧은 문장을 추가합니다 (예: '환경설정 저장').
  3. 저장을 클릭합니다.

  1. 조건에서 사용자가 계정 연결을 완료한 경우를 클릭합니다.
  2. 사용자가 계정 연결에 동의하는 경우 흐름을 어떻게 진행할지 구성합니다. 예를 들어 웹훅을 호출하여 필요한 맞춤 비즈니스 로직을 처리하고 원래 장면으로 다시 전환할 수 있습니다.
  3. 저장을 클릭합니다.

  1. 조건에서 사용자가 계정 연결을 취소하거나 닫은 경우를 클릭합니다.
  2. 사용자가 계정 연결에 동의하지 않는 경우 흐름을 진행하는 방법을 구성합니다. 예를 들어 확인 메시지를 보내고 계정 연결이 필요하지 않은 기능을 제공하는 장면으로 리디렉션합니다.
  3. 저장을 클릭합니다.

  1. 조건에서 시스템 또는 네트워크 오류가 발생한 경우를 클릭합니다.
  2. 시스템 또는 네트워크 오류로 인해 계정 연결 흐름을 완료할 수 없는 경우 흐름을 진행하는 방법을 구성합니다. 예를 들어 확인 메시지를 보내고 계정 연결이 필요하지 않은 기능을 제공하는 장면으로 리디렉션합니다.
  3. 저장을 클릭합니다.

데이터 액세스 요청 처리

Assistant 요청에 액세스 토큰이 포함되어 있으면 먼저 액세스 토큰이 유효하고 만료되지 않았는지 확인한 후 데이터베이스에서 연결된 사용자 계정을 검색합니다.