OAuth로 인증

OAuth를 사용하면 에이전트가 사용자의 신원을 확인하고 대화에서 맞춤설정된 정보를 안전한 방식으로 제공할 수 있습니다. 사용자가 신뢰할 수 있는 OAuth 제공업체에 로그인하도록 하면 에이전트가 자동화를 통해 빠른 답변을 제공하고 실시간 에이전트의 시간을 절약할 수 있는 사용자 데이터에 액세스할 수 있습니다.

Business Messages는 에이전트에 대해 구성한 OAuth 제공업체에 로그인하라는 메시지를 표시하는 인증 요청 제안사항으로 OAuth 2.0을 지원합니다. 사용자가 정상적으로 로그인하면 Business Messages가 승인 코드를 에이전트에 메시지로 다시 전달합니다.

OAuth 제공업체의 승인 코드를 받으면 API와 통합하고 사용자 ID 정보가 필요한 대화 흐름을 지원할 수 있습니다. 상호작용하는 각 서비스에는 자체 이용약관이 있습니다.

에이전트의 OAuth 구성

에이전트에 인증 요청 제안을 사용 설정하려면 먼저 OAuth를 구성해야 합니다.

OAuth 구성을 지정하려면 Business Communications API로 PATCH 요청을 수행하여 에이전트의 endpointUrl 필드를 업데이트합니다.

엔드포인트 URL을 지정한 후에는 에이전트의 리디렉션 URI를 저장하고 OAuth 제공업체 정보에서 리디렉션 URI를 업데이트해야 합니다.

기본 요건

다음 항목이 필요합니다.

  • OAuth 2.0 사양을 따르는 OAuth 제공업체
  • 개발 머신의 GCP 프로젝트 서비스 계정 키 경로
  • 에이전트 name(예: "brands/12345/agents/67890")

    에이전트의 name를 모르는 경우 브랜드의 모든 에이전트 나열을 참조하세요.

  • 사용자가 OAuth 제공업체에 로그인하는 엔드포인트 URL

업데이트 요청 보내기

에이전트를 업데이트하려면 다음 명령어를 실행합니다. 변수를 기본 요건에서 식별한 값으로 바꿉니다.

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=businessMessagesAgent.authorizationConfig" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
    'businessMessagesAgent': {
        'authorizationConfig': {
            'endpointUrl': 'ENDPOINT_URL',
        },
    },
}"

리디렉션 URI 업데이트

에이전트에 OAuth가 구성되었으므로 OAuth 제공업체에 다음 4개의 리디렉션 URI를 추가해야 합니다.

  • https://business.google.com/callback
  • https://business.google.com/callback?
  • https://business.google.com/message?az-intent-type=1
  • https://business.google.com/message?az-intent-type=1&

OAuth 제공업체 정보에 모든 리디렉션 URL을 포함해야 합니다.

리디렉션 URI를 업데이트하는 프로세스는 OAuth 제공업체에 따라 다릅니다. 자세한 내용은 OAuth 제공업체를 참고하세요.

에이전트에 OAuth가 구성되었으므로 인증 요청 제안으로 사용자를 인증할 수 있습니다.

사용자 인증

에이전트에 OAuth를 구성한 후 사용자에게 인증 요청 제안을 통해 로그인하라는 메시지를 표시할 수 있습니다.

기본 요건

다음 항목이 필요합니다.

  • 개발 머신의 GCP 프로젝트 서비스 계정 키 경로
  • 에이전트 name(예: "brands/12345/agents/67890")

    에이전트의 name를 모르는 경우 브랜드의 모든 에이전트 나열을 참조하세요.

  • OAuth 제공업체의 클라이언트 ID

  • OAuth 제공업체의 코드 보안 질문 요구사항

  • OAuth 제공업체의 범위

인증 요청 추천 보내기

인증 요청 제안

사용자를 인증하려면 다음 단계를 따르세요.

  1. OAuth 요청을 위한 코드 확인자 및 코드 요청 문자열을 생성합니다. 요구사항 및 옵션은 OAuth 제공업체를 참고하세요.
  2. 인증 요청 제안이 포함된 메시지를 전송합니다.

cURL

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     https://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This code sends a text message to the user with an authentication request suggestion
# that allows the user to authenticate with OAuth. It also has a fallback text.
# Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#authentication-request-suggestion

# Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to
# Make sure a service account key file exists at ./service_account_key.json
# Replace the __CLIENT_ID__
# Replace the __CODE_CHALLENGE__
# Replace the __SCOPE__

curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-messages" \
-H "$(oauth2l header --json ./service_account_key.json businessmessages)" \
-d "{
    'messageId': '$(uuidgen)',
    'text': 'Sign in to continue the conversation.',
    'fallback': 'Visit support.growingtreebank.com to continue.',
    'suggestions': [
      {
        'authenticationRequest': {
          'oauth': {
            'clientId': '__CLIENT_ID__',
            'codeChallenge': '__CODE_CHALLENGE__',
            'scopes': [
              '__SCOPE__',
            ],
          },
        },
      },
    ],
    'representative': {
      'avatarImage': 'https://developers.google.com/identity/images/g-logo.png',
      'displayName': 'Chatbot',
      'representativeType': 'BOT'
    }
  }"

Node.js


/**
 * This code sends a text message to the user with an authentication request suggestion
 * that allows the user to authenticate with OAuth. It also has a fallback text.
 * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#authentication-request-suggestion
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js
 * Business Messages client library.
 */

/**
 * Before continuing, learn more about the prerequisites for authenticating
 * with OAuth at: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/oauth?hl=en
 *
 * Edit the values below:
 */
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';
const CONVERSATION_ID = 'EDIT_HERE';
const OAUTH_CLIENT_ID = 'EDIT_HERE';
const OAUTH_CODE_CHALLENGE = 'EDIT_HERE';
const OAUTH_SCOPE = 'EDIT_HERE';

const businessmessages = require('businessmessages');
const uuidv4 = require('uuid').v4;
const {google} = require('googleapis');

// Initialize the Business Messages API
const bmApi = new businessmessages.businessmessages_v1.Businessmessages({});

// Set the scope that we need for the Business Messages API
const scopes = [
  'https://www.googleapis.com/auth/businessmessages',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

/**
 * Posts a message to the Business Messages API along with an authentication request.
 *
 * @param {string} conversationId The unique id for this user and agent.
 * @param {string} representativeType A value of BOT or HUMAN.
 */
async function sendMessage(conversationId, representativeType) {
  const authClient = await initCredentials();

  if (authClient) {
    // Create the payload for sending a message along with an authentication request
    const apiParams = {
      auth: authClient,
      parent: 'conversations/' + conversationId,
      resource: {
        messageId: uuidv4(),
        representative: {
          representativeType: representativeType,
        },
        fallback: 'Visit support.growingtreebank.com to continue.',
        text: 'Sign in to continue the conversation.',
        suggestions: [
          {
            authenticationRequest: {
              oauth: {
                clientId: OAUTH_CLIENT_ID,
                codeChallenge: OAUTH_CODE_CHALLENGE,
                scopes: [OAUTH_SCOPE]
              }
            }
          },
        ],
      },
    };

    // Call the message create function using the
    // Business Messages client library
    bmApi.conversations.messages.create(apiParams,
      {auth: authClient}, (err, response) => {
      console.log(err);
      console.log(response);
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

sendMessage(CONVERSATION_ID, 'BOT');

Python


"""Sends a text message to the user with an authentication request suggestion.

It allows the user to authenticate with OAuth and has a fallback text.
Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#authentication-request-suggestion

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

import uuid

from businessmessages import businessmessages_v1_client as bm_client
from businessmessages.businessmessages_v1_messages import BusinessMessagesAuthenticationRequest
from businessmessages.businessmessages_v1_messages import BusinessMessagesAuthenticationRequestOauth
from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest
from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage
from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative
from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion
from oauth2client.service_account import ServiceAccountCredentials

# Before continuing, learn more about the prerequisites for authenticating
# with OAuth at: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/oauth?hl=en

# Edit the values below:
path_to_service_account_key = './service_account_key.json'
conversation_id = 'EDIT_HERE'
oauth_client_id = 'EDIT_HERE'
oauth_code_challenge = 'EDIT_HERE'
oauth_scope = 'EDIT_HERE'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    path_to_service_account_key,
    scopes=['https://www.googleapis.com/auth/businessmessages'])

client = bm_client.BusinessmessagesV1(credentials=credentials)

representative_type_as_string = 'BOT'
if representative_type_as_string == 'BOT':
  representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT
else:
  representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN

# Create a text message with an authentication request
message = BusinessMessagesMessage(
    messageId=str(uuid.uuid4().int),
    representative=BusinessMessagesRepresentative(
        representativeType=representative_type
    ),
    text='Sign in to continue the conversation.',
    fallback='Visit support.growingtreebank.com to continue.',
    suggestions=[
        BusinessMessagesSuggestion(
            authenticationRequest=BusinessMessagesAuthenticationRequest(
                oauth=BusinessMessagesAuthenticationRequestOauth(
                    clientId=oauth_client_id,
                    codeChallenge=oauth_code_challenge,
                    scopes=[oauth_scope])
                )
            ),
        ]
    )

# Create the message request
create_request = BusinessmessagesConversationsMessagesCreateRequest(
    businessMessagesMessage=message,
    parent='conversations/' + conversation_id)

# Send the message
bm_client.BusinessmessagesV1.ConversationsMessagesService(
    client=client).Create(request=create_request)
  1. 사용자가 추천 문장을 탭하고 로그인하면 에이전트의 웹훅에서 메시지가 수신됩니다. authenticationResponse.code 필드에서 승인 코드를 검색합니다.

메시지를 수신하면 승인 코드와 코드 인증기를 OAuth 제공업체의 액세스 토큰으로 교환할 수 있습니다. 액세스 토큰을 사용하여 사용자 데이터에 액세스할 수 있습니다.

코드 샘플을 포함하여 인증이 포함된 샘플 대화는 사용자 인증을 참조하세요.