Penautan Akun Google dengan OAuth

Akun ditautkan menggunakan alur implisit dan kode otorisasi OAuth 2.0 standar industri. Layanan Anda harus mendukung endpoint otorisasi dan pertukaran token yang mematuhi OAuth 2.0.

隐式流程中,Google 会在用户的浏览器中打开您的授权端点。成功登录后,您将向 Google 返回一个长期访问令牌。现在,此访问令牌会包含在 Google 发送的每个请求中。

授权代码流程中,您需要两个端点:

  • 授权端点,用于向尚未登录的用户显示登录界面。授权端点还会创建一个短期授权代码,以记录用户对所请求访问权限的同意情况。

  • 令牌交换端点,负责两种类型的交换:

    1. 使用授权代码换取长期有效的刷新令牌和短期有效的访问令牌。当用户完成账号关联流程时,就会发生此交换。
    2. 将长期有效的刷新令牌换成短期有效的访问令牌。当 Google 需要新的访问令牌(因为现有访问令牌已过期)时,就会发生这种交换。

选择 OAuth 2.0 流程

虽然隐式流程更易于实现,但 Google 建议通过隐式流程签发的访问令牌永不过期。这是因为,在隐式流程中,令牌过期后,系统会强制用户重新关联其账号。如果您出于安全考虑需要令牌过期,我们强烈建议您改用授权码流程。

设计准则

本部分介绍了您为 OAuth 关联流程托管的用户屏幕的设计要求和建议。在 Google 应用调用该 API 后,您的平台会向用户显示登录 Google 页面和账号关联意见征求界面。同意关联账号后,系统会将用户重定向回 Google 的应用。

此图展示了用户将其 Google 账号与您的身份验证系统相关联的步骤。第一个屏幕截图显示了用户从您的平台发起的关联。第二张图片显示用户登录 Google,第三张图片显示用户同意并确认将其 Google 账号与您的应用相关联。最后一张屏幕截图显示 Google 应用中成功关联的用户账号。
图 1.账号关联用户登录 Google 和同意屏幕。

要求

  1. 您必须说明用户的账号将与 Google 相关联,而非 Google Home 或 Google 助理等特定 Google 产品相关联。

建议

建议您执行以下操作:

  1. 显示 Google 的隐私权政策。在同意屏幕上添加指向 Google 隐私权政策的链接。

  2. 要共享的数据。使用清晰简洁的语言告知用户 Google 需要哪些用户数据以及原因。

  3. 添加醒目的号召性用语。在用户同意页面上提供明确的号召性用语,例如“同意并关联”。这是因为用户需要了解他们需要与 Google 分享哪些数据才能关联账号。

  4. 可以取消。为用户提供返回或取消链接的途径,如果用户选择不进行关联。

  5. 明确的登录流程。确保用户有明确的 Google 账号登录方法,例如用户名和密码字段或使用 Google 账号登录

  6. 能够解除关联。提供一种可让用户解除关联的机制,例如指向您平台上账号设置的网址。或者,您也可以添加指向 Google 账号的链接,以便用户管理其关联的账号。

  7. 能够更改用户账号。建议用户切换账号的方法。如果用户通常拥有多个账号,这种做法尤为有益。

    • 如果用户必须关闭意见征求界面才能切换账号,请向 Google 发送可恢复的错误,以便用户可以使用 OAuth 关联隐式流程登录所需的账号。
  8. 添加您的徽标。在意见征求页面上显示您的公司徽标。 按照您的样式准则放置徽标。如果您还想显示 Google 的徽标,请参阅徽标和商标

创建项目

如需创建使用账号关联的项目,请执行以下操作:

  1. 点击 Create project
  2. 输入名称或接受生成的建议。
  3. 确认或修改所有剩余字段。
  4. 点击创建

如需查看项目 ID,请执行以下操作:

  1. 在着陆页的表格中找到您的项目。项目 ID 会显示在 ID 列中。

Google 账号关联流程包含一个权限请求页面,该页面会告知用户哪个应用在请求访问其数据、请求访问哪些类型的数据,以及适用的条款。您需要先配置 OAuth 权限请求页面,然后才能生成 Google API 客户端 ID。

  1. 打开 Google API 控制台的 OAuth 同意屏幕页面。
  2. 如果出现提示,请选择您刚刚创建的项目。
  3. 在“OAuth 同意屏幕”页面上,填写表单,然后点击“保存”按钮。

    应用名称:征求用户同意的应用的名称。名称应准确反映您的应用,并与用户在其他位置看到的应用名称保持一致。应用名称将显示在账号关联权限请求界面上。

    应用徽标:权限请求页面上显示的一张图片,用以让用户认出您的应用。徽标会显示在账号关联权限请求页面和账号设置

    支持电子邮件地址:供用户就其同意问题与您联系。

    Google API 的范围:借助范围,您的应用可以访问用户的非公开 Google 数据。对于 Google 账号关联使用情形,默认范围(电子邮件地址、个人资料、openid)就足够了,您无需添加任何敏感范围。一般来说,最佳做法是在需要访问权限时逐步请求权限范围,而不是提前请求。了解详情

    已获授权的网域:为了保护您和您的用户,Google 只允许使用 OAuth 进行身份验证的应用使用已获授权的网域。应用的链接必须托管在已获授权的网域上。了解详情

    应用首页链接:应用的首页。必须托管在已获授权的网域上。

    应用隐私权政策链接:显示在 Google 账号关联意见征求界面上。必须托管在已获授权的网域上。

    应用服务条款链接(可选):必须托管在已获授权的网域上。

    图 1. 虚构应用 Tunery 的 Google 账号关联意见征求界面

  4. 查看“验证状态”,如果您的应用需要验证,请点击“提交以供验证”按钮,提交应用以供验证。如需了解详情,请参阅 OAuth 验证要求

Menerapkan server OAuth

To support the OAuth 2.0 implicit flow, your service makes an authorization endpoint available by HTTPS. This endpoint is responsible for authentication and 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.

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

A typical OAuth 2.0 implicit flow session initiated by Google has the following flow:

  1. Google opens your authorization endpoint in the user's browser. 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.
  2. Your service creates an access token and returns it to Google. To do so, redirect the user's browser back to Google with the access token attached to the request.
  3. Google calls your service's APIs and attaches the access token with each request. Your service verifies that the access token grants Google authorization to access the API and then completes the API call.

Handle authorization requests

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

Authorization endpoint parameters
client_id The client ID you assigned to 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.
response_type The type of value to return in the response. For the OAuth 2.0 implicit flow, the response type is always token.
user_locale The Google Account language setting in RFC5646 format used to localize your content in the user's preferred language.

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

GET https://myservice.example.com/auth?client_id=GOOGLE_CLIENT_ID&redirect_uri=REDIRECT_URI&state=STATE_STRING&response_type=token&user_locale=LOCALE

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

  1. Verify the client_id and redirect_uri values to prevent granting access to unintended or misconfigured client apps:

    • Confirm that the client_id matches the client ID you assigned to Google.
    • Confirm that the URL specified by the redirect_uri parameter has the following form:
      https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID
      https://oauth-redirect-sandbox.googleusercontent.com/r/YOUR_PROJECT_ID
      
  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 access token for Google to use to access your API. The access token can be any string value, but it must uniquely represent the user and the client the token is for and must not be guessable.

  4. Send an HTTP response that redirects the user's browser to the URL specified by the redirect_uri parameter. Include all of the following parameters in the URL fragment:

    • access_token: The access token you just generated
    • token_type: The string bearer
    • state: The unmodified state value from the original request

    The following is an example of the resulting URL:

    https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID#access_token=ACCESS_TOKEN&token_type=bearer&state=STATE_STRING

Google's OAuth 2.0 redirect handler receives the access token and confirms that the state value hasn't changed. After Google has obtained an access token for your service, Google attaches the token to subsequent calls to your service APIs.

Menangani permintaan info pengguna

Endpoint userinfo adalah resource yang dilindungi OAuth 2.0 yang menampilkan klaim tentang pengguna yang ditautkan. Menerapkan dan menghosting endpoint userinfo bersifat opsional, kecuali untuk kasus penggunaan berikut:

Setelah token akses berhasil diambil dari endpoint token Anda, Google akan mengirimkan permintaan ke endpoint userinfo Anda untuk mengambil informasi profil dasar tentang pengguna yang ditautkan.

header permintaan endpoint userinfo
Authorization header Token akses jenis Bearer.

Misalnya, jika endpoint userinfo Anda tersedia di https://myservice.example.com/userinfo, permintaan mungkin akan terlihat seperti berikut:

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

Agar endpoint userinfo Anda dapat menangani permintaan, lakukan langkah-langkah berikut:

  1. Ekstrak token akses dari header Otorisasi dan tampilkan informasi untuk pengguna yang terkait dengan token akses.
  2. Jika token akses tidak valid, tampilkan error HTTP 401 Tidak Sah dengan menggunakan Header Respons WWW-Authenticate. Berikut adalah contoh respons error userinfo:
    HTTP/1.1 401 Unauthorized
    WWW-Authenticate: error="invalid_token",
    error_description="The Access Token expired"
    
    Jika pesan error 401 Tidak Sah, atau respons error lainnya yang tidak berhasil ditampilkan selama proses penautan, error tersebut tidak akan dapat dipulihkan, token yang diambil akan dihapus dan pengguna harus memulai proses penautan lagi.
  3. Jika token akses valid, tampilkan dan respons HTTP 200 dengan objek JSON berikut dalam isi HTTPS respons:

    {
    "sub": "USER_UUID",
    "email": "EMAIL_ADDRESS",
    "given_name": "FIRST_NAME",
    "family_name": "LAST_NAME",
    "name": "FULL_NAME",
    "picture": "PROFILE_PICTURE",
    }
    Jika endpoint userinfo Anda menampilkan respons sukses HTTP 200, token dan klaim yang diambil akan didaftarkan terhadap Akun Google pengguna.

    respons endpoint userinfo
    sub ID unik yang mengidentifikasi pengguna di sistem Anda.
    email Alamat email pengguna.
    given_name Opsional: Nama depan pengguna.
    family_name Opsional: Nama belakang pengguna.
    name Opsional: Nama lengkap pengguna.
    picture Opsional: Foto profil pengguna.

Memvalidasi implementasi

Anda dapat memvalidasi penerapan menggunakan alat OAuth 2.0 Playground.

Di alat ini, lakukan langkah-langkah berikut:

  1. Klik Configuration untuk membuka jendela OAuth 2.0 Configuration.
  2. Di kolom OAuth flow, pilih Client-side.
  3. Di kolom OAuth Endpoints, pilih Custom.
  4. Tentukan endpoint OAuth 2.0 dan client ID yang Anda tetapkan ke Google di kolom yang sesuai.
  5. Di bagian Langkah 1, jangan pilih cakupan Google apa pun. Sebagai gantinya, biarkan kolom ini kosong atau ketik cakupan yang valid untuk server Anda (atau string arbitrer jika Anda tidak menggunakan cakupan OAuth). Setelah selesai, klik Otorisasi API.
  6. Di bagian Langkah 2 dan Langkah 3, ikuti alur OAuth 2.0 dan verifikasi bahwa setiap langkah berfungsi sebagaimana mestinya.

Anda dapat memvalidasi penerapan menggunakan alat Demo Penautan Akun Google.

Di alat tersebut, lakukan langkah-langkah berikut:

  1. Klik tombol Login dengan Google.
  2. Pilih akun yang ingin ditautkan.
  3. Masukkan ID layanan.
  4. Secara opsional, masukkan satu atau beberapa cakupan yang akan Anda minta aksesnya.
  5. Klik Mulai Demo.
  6. Jika diminta, konfirmasi bahwa Anda dapat mengizinkan dan menolak permintaan penautan.
  7. Pastikan Anda dialihkan ke platform Anda.