Liên kết tài khoản với OAuth

Loại liên kết OAuth hỗ trợ 2 quy trình OAuth 2.0 tiêu chuẩn ngành là quy trình mã ngầm ẩnuỷ quyền.

Trong luồng mã ngầm định, Google sẽ mở điểm cuối ủy quyền của bạn trong trình duyệt của người dùng. Sau khi đăng nhập thành công, bạn sẽ trả về một mã thông báo truy cập dài hạn cho Google. Mã thông báo truy cập này hiện được đưa vào mọi yêu cầu gửi từ Trợ lý tới Hành động của bạn.

Trong quy trình mã uỷ quyền, bạn cần có 2 điểm cuối:

  • Điểm cuối uỷ quyền (trách nhiệm trình bày giao diện người dùng đăng nhập cho người dùng chưa đăng nhập và ghi lại sự đồng ý đối với quyền truy cập được yêu cầu dưới dạng mã uỷ quyền ngắn hạn).
  • Điểm cuối token exchange chịu trách nhiệm về hai hình thức trao đổi:
    1. Trao đổi một mã ủy quyền để lấy mã làm mới trong thời gian dài và một mã truy cập ngắn hạn. Quá trình trao đổi này diễn ra khi người dùng trải qua quy trình liên kết tài khoản.
    2. Trao đổi mã làm mới trong thời gian dài để lấy mã truy cập ngắn hạn. Quá trình trao đổi này diễn ra khi Google cần một mã truy cập mới vì mã này đã hết hạn.

Mặc dù quy trình mã ngầm định đơn giản hơn nên triển khai, bạn nên sử dụng các mã thông báo truy cập được phát hành bằng quy trình ngầm ẩn, vì việc sử dụng mã thông báo hết hạn với luồng ngầm định sẽ buộc người dùng liên kết lại tài khoản của họ. Nếu cần mã hết hạn vì lý do bảo mật, bạn nên cân nhắc sử dụng quy trình mã xác thực.

Triển khai liên kết tài khoản OAuth

Định cấu hình dự án

Để định cấu hình dự án nhằm sử dụng tính năng liên kết OAuth, hãy làm theo các bước sau:

  1. Mở Bảng điều khiển Actions rồi chọn dự án mà bạn muốn sử dụng.
  2. Nhấp vào thẻ Phát triển rồi chọn Liên kết tài khoản.
  3. Bật nút chuyển bên cạnh Liên kết tài khoản.
  4. Trong phần Tạo tài khoản, hãy chọn Không, tôi chỉ muốn cho phép tạo tài khoản trên trang web của mình.
  5. Trong Loại liên kết, hãy chọn OAuthMã uỷ quyền.

  6. Trong phần Thông tin khách hàng:

    • Chỉ định một giá trị cho Mã ứng dụng khách do Hành động của bạn gửi cho Google để xác định các yêu cầu đến từ Google.
    • Ghi lại giá trị của Mã ứng dụng khách do Google cấp cho Hành động của bạn;
    • Chèn URL cho điểm cuối Uỷ quyền và Trao đổi mã thông báo của bạn.
  1. Nhấp vào Lưu.

Triển khai máy chủ 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
    }

Thiết kế giao diện người dùng bằng giọng nói cho quy trình xác thực

Kiểm tra xem người dùng đã được xác minh hay chưa và bắt đầu quy trình liên kết tài khoản

  1. Mở dự án Trình tạo hành động trong Bảng điều khiển Actions.
  2. Tạo một cảnh mới để bắt đầu liên kết tài khoản trong Hành động của bạn:
    1. Nhấp vào Cảnh.
    2. Nhấp vào biểu tượng thêm (+) để thêm một cảnh mới.
  3. Trong cảnh mới tạo, hãy nhấp vào biểu tượng thêm cho Điều kiện.
  4. Thêm một điều kiện kiểm tra xem người dùng liên kết với cuộc trò chuyện có phải là người dùng đã xác minh hay không. Nếu quy trình kiểm tra không thành công, thì Hành động của bạn không thể thực hiện liên kết tài khoản trong cuộc trò chuyện và nên quay lại cung cấp quyền truy cập vào chức năng không yêu cầu liên kết tài khoản.
    1. Trong trường Enter new expression trong phần Điều kiện, hãy nhập logic sau: user.verificationStatus != "VERIFIED"
    2. Trong Chuyển đổi, hãy chọn một cảnh không yêu cầu liên kết tài khoản hoặc một cảnh là điểm truy cập vào chức năng chỉ dành cho khách.

  1. Nhấp vào biểu tượng thêm cho Điều kiện.
  2. Thêm điều kiện để kích hoạt quy trình liên kết tài khoản nếu người dùng không có danh tính được liên kết.
    1. Trong trường Enter new expression trong phần Điều kiện, hãy nhập logic sau: user.verificationStatus == "VERIFIED"
    2. Trong Chuyển đổi, hãy chọn cảnh hệ thống Liên kết tài khoản.
    3. Nhấp vào Lưu.

Sau khi lưu, một cảnh hệ thống liên kết tài khoản mới có tên là <SceneName>_AccountLinking sẽ được thêm vào dự án của bạn.

Tuỳ chỉnh cảnh liên kết tài khoản

  1. Trong Cảnh, hãy chọn cảnh hệ thống liên kết tài khoản.
  2. Nhấp vào Gửi lời nhắc rồi thêm một câu ngắn để mô tả cho người dùng lý do Hành động đó cần truy cập vào danh tính của họ (ví dụ: "Để lưu lựa chọn ưu tiên của bạn").
  3. Nhấp vào Lưu.

  1. Trong mục Điều kiện, hãy nhấp vào Nếu người dùng hoàn tất thành công quá trình liên kết tài khoản.
  2. Thiết lập cách quy trình diễn ra nếu người dùng đồng ý liên kết tài khoản của họ. Ví dụ: gọi webhook để xử lý mọi logic kinh doanh tuỳ chỉnh bắt buộc và chuyển đổi lại cảnh ban đầu.
  3. Nhấp vào Lưu.

  1. Trong mục Điều kiện, hãy nhấp vào Nếu người dùng huỷ hoặc huỷ quy trình liên kết tài khoản.
  2. Thiết lập cách quy trình diễn ra nếu người dùng không đồng ý liên kết tài khoản của họ. Ví dụ: gửi thông báo xác nhận và chuyển hướng đến các cảnh cung cấp chức năng không yêu cầu liên kết tài khoản.
  3. Nhấp vào Lưu.

  1. Trong mục Điều kiện, hãy nhấp vào Nếu xảy ra lỗi hệ thống hoặc mạng.
  2. Định cấu hình cách tiến hành của quy trình nếu quy trình liên kết tài khoản không thể hoàn tất do lỗi hệ thống hoặc mạng. Ví dụ: gửi thông báo xác nhận và chuyển hướng đến các cảnh cung cấp chức năng không yêu cầu liên kết tài khoản.
  3. Nhấp vào Lưu.

Xử lý các yêu cầu truy cập dữ liệu

Nếu yêu cầu Trợ lý chứa mã truy cập, trước tiên, hãy kiểm tra để đảm bảo rằng mã truy cập này là hợp lệ (và chưa hết hạn), sau đó truy xuất tài khoản người dùng được liên kết từ cơ sở dữ liệu của bạn.