Akun ditautkan menggunakan alur kode otorisasi OAuth 2.0 standar industri.
OAuth 2.1 &PKCE untuk Agen
Untuk agen AI tanpa status dan pipeline multi-modal, sebaiknya terapkan OAuth 2.1.
- PKCE (Proof Key for Code Exchange): Harus digunakan untuk mengamankan alur kode otorisasi, sehingga mencegah serangan intersepsi.
- Tidak Ada Alur Implisit: Alur implisit mengekspos token akses di URL, yang merupakan risiko keamanan untuk lingkungan agen.
Layanan Anda harus mendukung endpoint pertukaran token dan otorisasi yang sesuai dengan OAuth 2.0/2.1.
Create the project
To create your project to use account linking:
- Go to the Google API Console.
- Click Create project.
- Enter a name or accept the generated suggestion.
- Confirm or edit any remaining fields.
- Click Create.
To view your project ID:
- Go to the Google API Console.
- Find your project in the table on the landing page. The project ID appears in the ID column.
Configure your OAuth Consent Screen
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.
- Open the OAuth consent screen page of the Google APIs console.
- If prompted, select the project you just created.
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
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.
Mengimplementasikan server OAuth
Implementasi server OAuth 2.0 dari alur kode otorisasi terdiri dari dua endpoint, yang disediakan oleh layanan Anda melalui HTTPS. Endpoint pertama adalah endpoint otorisasi, yang bertanggung jawab untuk menemukan atau mendapatkan izin dari pengguna untuk akses data. Endpoint otorisasi menampilkan UI login kepada pengguna Anda yang belum login dan mencatat izin untuk akses yang diminta. Endpoint kedua adalah endpoint pertukaran token, yang digunakan untuk mendapatkan string terenkripsi, yang disebut token, yang mengotorisasi pengguna untuk mengakses layanan Anda.
Saat aplikasi Google perlu memanggil salah satu API layanan Anda, Google menggunakan endpoint ini bersama-sama untuk mendapatkan izin dari pengguna Anda untuk memanggil API ini atas nama mereka.
Penautan Akun Google: Alur Kode Otorisasi OAuth
Diagram urutan berikut menjelaskan interaksi antara Pengguna, Google, dan endpoint layanan Anda.
Peran dan tanggung jawab
Tabel berikut menentukan peran dan tanggung jawab aktor dalam alur OAuth Penautan Akun Google (GAL). Perhatikan bahwa di GAL, Google bertindak sebagai Klien OAuth, sedangkan layanan Anda bertindak sebagai Penyedia Identitas/Layanan.
| Aktor / Komponen | Peran GAL | Tanggung Jawab |
|---|---|---|
| Aplikasi / Server Google | Klien OAuth | Memulai alur, menerima kode otorisasi, menukarnya dengan token, dan menyimpannya dengan aman untuk mengakses API layanan Anda. |
| Endpoint Otorisasi Anda | Server Otorisasi | Mengautentikasi pengguna Anda dan mendapatkan izin mereka untuk membagikan akses ke data mereka kepada Google. |
| Endpoint Pertukaran Token Anda | Server Otorisasi | Memvalidasi kode otorisasi dan token refresh, serta menerbitkan token akses ke Server Google. |
| URI Pengalihan Google | Endpoint Callback | Menerima pengalihan pengguna dari layanan otorisasi Anda dengan nilai
code dan state. |
Sesi alur kode otorisasi OAuth 2.0 yang dimulai oleh Google memiliki alur berikut:
- Google membuka endpoint otorisasi Anda di browser pengguna. Jika alur dimulai di perangkat khusus suara untuk Tindakan, Google akan mentransfer eksekusi ke ponsel.
- Pengguna login, jika belum login, dan memberikan izin kepada Google untuk mengakses data mereka dengan API Anda, jika mereka belum memberikan izin.
- Layanan Anda membuat kode otorisasi dan menampilkannya ke Google. Untuk melakukannya, alihkan browser pengguna kembali ke Google dengan kode otorisasi yang dilampirkan ke permintaan.
- Google mengirimkan kode otorisasi ke endpoint pertukaran token Anda, yang memverifikasi keaslian kode dan menampilkan token akses dan token refresh. Token akses adalah token berumur pendek yang diterima layanan Anda sebagai kredensial untuk mengakses API. Token refresh adalah token berumur panjang yang dapat disimpan dan digunakan Google untuk mendapatkan token akses baru saat masa berlakunya berakhir.
- Setelah pengguna menyelesaikan alur penautan akun, setiap permintaan berikutnya yang dikirim dari Google akan berisi token akses.
Resep Implementasi
Ikuti langkah-langkah berikut untuk mengimplementasikan alur Kode Otorisasi.
Langkah 1: Menangani permintaan otorisasi
Saat Google memulai penautan akun, Google akan mengalihkan pengguna ke endpoint otorisasi Anda. Untuk mengetahui detail kontrak protokol dan persyaratan parameter, lihat Endpoint Otorisasi.
Untuk menangani permintaan, lakukan tindakan berikut:
Validasi permintaan:
- Pastikan
client_idcocok dengan Client ID yang ditetapkan ke Google. - Pastikan
redirect_uricocok dengan URL pengalihan Google yang diharapkan:none https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID https://oauth-redirect-sandbox.googleusercontent.com/r/YOUR_PROJECT_ID - Pastikan
response_typeadalahcode.
- Pastikan
Autentikasi pengguna:
- Periksa apakah pengguna login ke layanan Anda.
- Jika pengguna tidak login, minta mereka untuk menyelesaikan alur login atau pendaftaran Anda.
Buat kode otorisasi:
- Buat kode otorisasi unik yang tidak dapat ditebak dan terkait dengan pengguna dan klien.
- Tetapkan masa berlaku kode menjadi sekitar 10 menit.
Alihkan kembali ke Google:
- Alihkan browser ke URL yang diberikan di
redirect_uri. - Tambahkan parameter kueri berikut:
code: Kode otorisasi yang Anda buat.state: Nilai status yang tidak diubah yang diterima dari Google.
- Alihkan browser ke URL yang diberikan di
Langkah 2: Menangani permintaan pertukaran token
Endpoint pertukaran token Anda memproses dua jenis permintaan: menukar kode dengan token, dan memperbarui token akses yang masa berlakunya telah berakhir. Untuk mengetahui detail kontrak protokol dan persyaratan parameter, lihat Endpoint Pertukaran Token.
A. Menukar kode otorisasi dengan token
Saat menerima kode otorisasi, Google akan memanggil endpoint pertukaran token Anda (POST) untuk mengambil token.
Validasi permintaan:
- Verifikasi
client_iddanclient_secret. - Pastikan kode otorisasi valid dan masa berlakunya belum berakhir.
- Pastikan
redirect_uricocok dengan nilai yang digunakan di Langkah 1. - Jika validasi gagal, tampilkan HTTP
400 Bad Requestdengan{"error": "invalid_grant"}.
- Verifikasi
Terbitkan token:
- Buat
refresh_tokenberumur panjang danaccess_tokenberumur pendek (biasanya 1 jam). - Tampilkan
200 OKHTTP dengan respons token JSON standar.
- Buat
B. Memperbarui token akses
Saat masa berlaku token akses berakhir, Google akan meminta token baru menggunakan token refresh.
Validasi permintaan:
- Verifikasi
client_id,client_secret, danrefresh_token. - Jika validasi gagal, tampilkan HTTP
400 Bad Requestdengan{"error": "invalid_grant"}.
- Verifikasi
Terbitkan token akses baru:
- Buat
access_tokenberumur pendek baru. - Tampilkan
200 OKHTTP dengan respons token JSON (secara opsional menyertakan token refresh baru).
- Buat
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:
- Linked Account Sign-In with Google One Tap.
- Frictionless subscription on AndroidTV.
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:
- Extract access token from the Authorization header and return information for the user associated with the access token.
- If the access token is invalid, return an HTTP 401 Unauthorized error with using the
WWW-AuthenticateResponse Header. Below is an example of a userinfo error response: 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.HTTP/1.1 401 Unauthorized WWW-Authenticate: error="invalid_token", error_description="The Access Token expired"
If the access token is valid, return and HTTP 200 response with the following JSON object in the body of the HTTPS response:
If your userinfo endpoint returns an HTTP 200 success response, the retrieved token and claims are registered against the user's Google account.{ "sub": "USER_UUID", "email": "EMAIL_ADDRESS", "given_name": "FIRST_NAME", "family_name": "LAST_NAME", "name": "FULL_NAME", "picture": "PROFILE_PICTURE", }userinfo endpoint response subA unique ID that identifies the user in your system. emailEmail address of the user. given_nameOptional: First name of the user. family_nameOptional: Last name of the user. nameOptional: Full name of the user. pictureOptional: Profile picture of the user.
Memvalidasi implementasi
Anda dapat memvalidasi penerapan dengan menggunakan alat OAuth 2.0 Playground.
Di alat, lakukan langkah-langkah berikut:
- Klik Konfigurasi untuk membuka jendela Konfigurasi OAuth 2.0.
- Di kolom OAuth flow, pilih Client-side.
- Di kolom OAuth Endpoints, pilih Custom.
- Tentukan endpoint OAuth 2.0 dan client ID yang Anda tetapkan ke Google di kolom yang sesuai.
- 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 Izinkan API.
- Di bagian Langkah 2 dan Langkah 3, ikuti alur OAuth 2.0 dan verifikasi bahwa setiap langkah berfungsi sebagaimana mestinya.
Anda dapat memvalidasi penerapan dengan menggunakan alat Demo Penautan Akun Google.
Di alat, lakukan langkah-langkah berikut:
- Klik tombol Login dengan Google.
- Pilih akun yang ingin Anda tautkan.
- Masukkan ID layanan.
- Secara opsional, masukkan satu atau beberapa cakupan yang akan Anda minta aksesnya.
- Klik Mulai Demo.
- Jika diminta, konfirmasi bahwa Anda dapat menyetujui dan menolak permintaan penautan.
- Konfirmasi bahwa Anda dialihkan ke platform Anda.