Hesaplar, endüstri standardı OAuth 2.0 yetkilendirme kodu akışı kullanılarak bağlanır.
Aracılar için OAuth 2.1 ve PKCE
Durum bilgisiz yapay zeka aracıları ve çok modlu ardışık düzenler için OAuth 2.1 zorunlu kılınması önerilir.
- PKCE (Proof Key for Code Exchange): Yetkilendirme kodu akışını güvenli hale getirmek ve araya girme saldırılarını önlemek için kullanılmalıdır.
- Örtülü Akış Yok: Örtülü akış, URL'deki erişim jetonlarını kullanıma sunar. Bu durum, aracı ortamları için güvenlik riski oluşturur.
Hizmetiniz, OAuth 2.0/2.1 uyumlu yetkilendirme ve jeton değişimi uç noktalarını desteklemelidir.
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.
OAuth sunucunuzu uygulama
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 a user to access your service.
When a Google application 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.
Google Account Linking: OAuth Authorization Code Flow
The following sequence diagram details interactions between the User, Google, and your service's endpoints.
Roles and responsibilities
The following table defines the roles and responsibilities of the actors in the Google Account Linking (GAL) OAuth flow. Note that in GAL, Google acts as the OAuth Client, while your service acts as the Identity/Service Provider.
| Actor / Component | GAL Role | Responsibilities |
|---|---|---|
| Google App / Server | OAuth Client | Initiates the flow, receives the authorization code, exchanges it for tokens, and securely stores them to access your service's APIs. |
| Your Authorization Endpoint | Authorization Server | Authenticates your users and obtains their consent to share access to their data with Google. |
| Your Token Exchange Endpoint | Authorization Server | Validates authorization codes and refresh tokens, and issues access tokens to the Google Server. |
| Google Redirect URI | Callback Endpoint | Receives the user redirect from your authorization service with the
code and state values. |
An OAuth 2.0 authorization code flow session initiated by Google has the following flow:
- Google opens your authorization endpoint in the user's browser. If the flow started on a voice-only device for an Action, Google transfers the execution to a phone.
- 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.
- Your service creates an authorization code and returns it to Google. To do so, redirect the user's browser back to Google with the authorization code attached to the request.
- 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.
- After the user has completed the account linking flow, every subsequent request sent from Google contains an access token.
Implementation Recipe
Follow these steps to implement the Authorization Code flow.
Step 1: Handle authorization requests
When Google initiates account linking, it redirects the user to your authorization endpoint. For detailed protocol contracts and parameter requirements, see the Authorization Endpoint.
To handle the request, perform the following actions:
Validate the request:
- Confirm that the
client_idmatches the Client ID assigned to Google. - Confirm that the
redirect_urimatches the expected Google redirect URL:none https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID https://oauth-redirect-sandbox.googleusercontent.com/r/YOUR_PROJECT_ID - Verify that
response_typeiscode.
- Confirm that the
Authenticate the user:
- Check if the user is signed in to your service.
- If the user is not signed in, prompt them to complete your sign-in or sign-up flow.
Generate authorization code:
- Create a unique, non-guessable authorization code associated with the user and client.
- Set the code to expire in approximately 10 minutes.
Redirect back to Google:
- Redirect the browser to the URL provided in
redirect_uri. - Append the following query parameters:
code: The authorization code you generated.state: The unmodified state value received from Google.
- Redirect the browser to the URL provided in
Step 2: Handle token exchange requests
Your token exchange endpoint processes two types of requests: exchanging codes for tokens, and refreshing expired access tokens. For detailed protocol contracts and parameter requirements, see the Token Exchange Endpoint.
A. Exchange authorization codes for tokens
When Google receives the authorization code, it calls your token exchange endpoint (POST) to retrieve tokens.
Validate the request:
- Verify
client_idandclient_secret. - Verify the authorization code is valid and not expired.
- Confirm
redirect_urimatches the value used in Step 1. - If validation fails, return an HTTP
400 Bad Requestwith{"error": "invalid_grant"}.
- Verify
Issue tokens:
- Generate a long-lived
refresh_tokenand a short-livedaccess_token(typically 1 hour). - Return an HTTP
200 OKwith the standard JSON token response.
- Generate a long-lived
B. Refresh access tokens
When the access token expires, Google requests a new one using the refresh token.
Validate the request:
- Verify
client_id,client_secret, andrefresh_token. - If validation fails, return an HTTP
400 Bad Requestwith{"error": "invalid_grant"}.
- Verify
Issue new access token:
- Generate a new short-lived
access_token. - Return an HTTP
200 OKwith the JSON token response (optionally including a new refresh token).
- Generate a new short-lived
Kullanıcı bilgileri isteklerini işleme
userinfo uç noktası, bağlı kullanıcıyla ilgili hak taleplerini döndüren, OAuth 2.0 korumalı bir kaynaktır. Kullanıcı bilgileri uç noktasını uygulamak ve barındırmak, aşağıdaki kullanım alanları hariç isteğe bağlıdır:
- Google One Tap ile Bağlı Hesapta Oturum Açma.
- AndroidTV'de sorunsuz abonelik.
Erişim jetonu, jeton uç noktanızdan başarıyla alındıktan sonra Google, bağlı kullanıcıyla ilgili temel profil bilgilerini almak için kullanıcı bilgileri uç noktanıza bir istek gönderir.
| kullanıcı bilgileri uç nokta istek başlıkları | |
|---|---|
Authorization header |
Taşıyıcı türündeki erişim jetonu. |
Örneğin, kullanıcı bilgileri uç noktanız
https://myservice.example.com/userinfo, talep aşağıdaki gibi görünebilir:
GET /userinfo HTTP/1.1 Host: myservice.example.com Authorization: Bearer ACCESS_TOKEN
Kullanıcı bilgileri uç noktanızın istekleri işlemesi için aşağıdaki adımları uygulayın:
- Yetkilendirme başlığından erişim jetonunu çıkarın ve erişim jetonuyla ilişkilendirilmiş kullanıcının bilgilerini döndürün.
- Erişim jetonu geçersizse
WWW-Authenticateyanıt üstbilgisini kullanarak HTTP 401 Yetkilendirilmemiş hatası döndürün. Aşağıda kullanıcı bilgileri hata yanıtı örneği verilmiştir: Bağlama işlemi sırasında 401 Yetkilendirilmedi veya başka bir başarısız hata yanıtı döndürülürse bu hata düzeltilemez, alınan jeton silinir ve kullanıcının bağlantı oluşturma işlemini yeniden başlatması gerekir.HTTP/1.1 401 Unauthorized WWW-Authenticate: error="invalid_token", error_description="The Access Token expired"
Erişim jetonu geçerliyse HTTPS gövdesinde aşağıdaki JSON nesnesiyle HTTP 200 yanıtını döndürün ve HTTP 200 yanıtını alın yanıt:
Kullanıcı bilgileri uç noktanız HTTP 200 başarılı yanıtı döndürürse alınan jeton ve hak talepleri kullanıcının Google Hesabı'na kaydedilir.{ "sub": "USER_UUID", "email": "EMAIL_ADDRESS", "given_name": "FIRST_NAME", "family_name": "LAST_NAME", "name": "FULL_NAME", "picture": "PROFILE_PICTURE", }userinfo uç nokta yanıtı subSisteminizdeki kullanıcıyı tanımlayan benzersiz bir kimlik. emailKullanıcının e-posta adresi. given_nameİsteğe bağlı: Kullanıcının adı. family_nameİsteğe bağlı: Kullanıcının soyadı. nameİsteğe bağlı: Kullanıcının tam adı. pictureİsteğe bağlı: Kullanıcının profil resmi.
Uygulamanızı doğrulama
OAuth 2.0 Playground aracını kullanarak uygulamanızı doğrulayabilirsiniz.
Araçta aşağıdaki adımları uygulayın:
- OAuth 2.0 Yapılandırma penceresini açmak için Yapılandırma'yı tıklayın.
- OAuth akışı alanında İstemci tarafı'nı seçin.
- OAuth Uç Noktaları alanında Özel'i seçin.
- OAuth 2.0 uç noktanızı ve Google'a atadığınız istemci kimliğini ilgili alanlarda belirtin.
- 1. adım bölümünde herhangi bir Google kapsamı seçmeyin. Bunun yerine bu alanı boş bırakın veya sunucunuz için geçerli bir kapsam yazın (OAuth kapsamları kullanmıyorsanız rastgele bir dize yazabilirsiniz). İşiniz bittiğinde API'leri yetkilendir'i tıklayın.
- 2. adım ve 3. adım bölümlerinde OAuth 2.0 akışını inceleyin ve her adımın beklendiği gibi çalıştığını doğrulayın.
Uygulamanızı Google Hesabı Bağlantısı Demosu aracını kullanarak doğrulayabilirsiniz.
Araçta aşağıdaki adımları uygulayın:
- Google ile oturum aç düğmesini tıklayın.
- Bağlamak istediğiniz hesabı seçin.
- Hizmet kimliğini girin.
- İsteğe bağlı olarak, erişim isteğinde bulunacağınız bir veya daha fazla kapsam girin.
- Start Demo'yu (Demoyu Başlat) tıklayın.
- İstendiğinde, bağlantı isteğini onaylayabileceğinizi ve reddedebileceğinizi onaylayın.
- Platformunuza yönlendirildiğinizi onaylayın.