Konta są łączone za pomocą standardowego w branży przepływu kodu autoryzacji OAuth 2.0.
OAuth 2.1 i PKCE w przypadku agentów
W przypadku bezstanowych agentów AI i wielomodowych potoków zalecane jest egzekwowanie OAuth 2.1.
- PKCE (Proof Key for Code Exchange): musi być używany do zabezpieczania przepływu kodu autoryzacji, co zapobiega atakom polegającym na przechwytywaniu.
- Brak przepływu niejawnego: przepływ niejawny udostępnia tokeny dostępu w adresie URL, co stanowi zagrożenie dla bezpieczeństwa środowisk agentów.
Usługa musi obsługiwać punkty końcowe autoryzacji i wymiany tokenów zgodne z OAuth 2.0/2.1.
Tworzenie projektu
Aby utworzyć projekt do łączenia kont:
- Otwórz konsolę interfejsów API Google.
- Kliknij Utwórz projekt.
- Wpisz nazwę lub zaakceptuj wygenerowaną sugestię.
- Potwierdź lub edytuj pozostałe pola.
- Kliknij Utwórz.
Aby wyświetlić identyfikator projektu:
- Otwórz konsolę interfejsów API Google.
- Znajdź swój projekt w tabeli na stronie docelowej. Identyfikator projektu jest wyświetlany w kolumnie Identyfikator.
Konfigurowanie ekranu zgody OAuth
Proces łączenia z kontem Google obejmuje ekran zgody, na którym użytkownicy mogą zobaczyć, która aplikacja prosi o dostęp do ich danych, jakich danych żąda i jakie warunki mają zastosowanie. Zanim wygenerujesz identyfikator klienta interfejsu API Google, musisz skonfigurować ekran zgody OAuth.
- Otwórz stronę ekranu zgody OAuth w konsoli interfejsów API Google.
- Jeśli pojawi się prośba, wybierz projekt, który właśnie utworzyłeś.
Na stronie „Ekran zgody OAuth” wypełnij formularz i kliknij przycisk „Zapisz”.
Nazwa aplikacji: nazwa aplikacji, która prosi o akceptację. Nazwa powinna dokładnie odzwierciedlać Twoją aplikację i być zgodna z nazwą aplikacji, którą użytkownicy widzą w innych miejscach. Nazwa aplikacji będzie wyświetlana na ekranie zgody na łączenie kont.
Logo aplikacji: obraz na ekranie zgody, który pomoże użytkownikom rozpoznać Twoją aplikację. Logo jest wyświetlane na ekranie zgody na łączenie kont i w ustawieniach konta.
Adres e-mail pomocy: dla użytkowników, którzy chcą się z Tobą skontaktować w sprawie pytań o ich zgodę.
Zakresy interfejsów API Google: zakresy umożliwiają aplikacji dostęp do prywatnych danych Google użytkownika. W przypadku łączenia z kontem Google wystarczy domyślny zakres (e-mail, profil, OpenID). Nie musisz dodawać żadnych zakresów wrażliwych. Zasadniczo najlepszym rozwiązaniem jest żądanie zakresów przyrostowo, w momencie, gdy wymagany jest dostęp, a nie z góry. Więcej informacji.
Autoryzowane domeny: aby chronić Ciebie i Twoich użytkowników, Google pozwala na używanie autoryzowanych domen tylko aplikacjom, które uwierzytelniają się za pomocą protokołu OAuth. Linki do Twoich aplikacji muszą być hostowane w autoryzowanych domenach. Więcej informacji.
Link do strony głównej aplikacji: strona główna Twojej aplikacji. Musi być hostowana w autoryzowanej domenie.
Link do polityki prywatności aplikacji: Wyświetlany na ekranie zgody na łączenie kont Google. Musi być hostowana w autoryzowanej domenie.
Link do Warunków korzystania z usługi (opcjonalnie): musi być hostowany w autoryzowanej domenie.
Rysunek 1. Ekran zgody na łączenie z kontem Google w przypadku fikcyjnej aplikacji Tunery
Sprawdź „Stan weryfikacji”. Jeśli Twoja aplikacja wymaga weryfikacji, kliknij przycisk „Prześlij do weryfikacji”, aby przesłać aplikację do weryfikacji. Szczegółowe informacje znajdziesz w wymaganiach dotyczących weryfikacji OAuth.
Wdrażanie serwera 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 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
Obsługa żądań informacji o użytkowniku
Punkt końcowy informacji o użytkowniku jest chronionym przez OAuth 2.0 zasobem, który zwraca deklaracje dotyczące połączonego użytkownika. Wdrożenie i hosting punktu końcowego informacji o użytkowniku jest opcjonalne. Wyjątkiem są te przypadki użycia:
- Logowanie się na połączone konto za pomocą Google One Tap
- Bezproblemowa subskrypcja na AndroidTV.
Po pobraniu tokena dostępu z punktu końcowego tokena Google wysyła żądanie do punktu końcowego informacji o użytkowniku, aby pobrać podstawowe informacje profilowe połączonego użytkownika.
| nagłówki żądań punktu końcowego informacji o użytkowniku | |
|---|---|
Authorization header |
Token dostępu typu okaziciela. |
Jeśli na przykład punkt końcowy informacji o użytkowniku jest dostępny pod adresem
https://myservice.example.com/userinfo, żądanie może wyglądać tak:
GET /userinfo HTTP/1.1 Host: myservice.example.com Authorization: Bearer ACCESS_TOKEN
Aby punkt końcowy informacji o użytkowniku mógł obsługiwać żądania, wykonaj te czynności:
- Wyodrębnij token dostępu z nagłówka autoryzacji i zwróć informacje o użytkowniku powiązanym z tym tokenem.
- Jeśli token dostępu jest nieprawidłowy, zwróć błąd HTTP 401 (Brak autoryzacji) i użyj nagłówka odpowiedzi
WWW-Authenticate. Poniżej znajduje się przykładowa odpowiedź na pytanie o błąd w informacjach o użytkowniku: Jeśli podczas procesu łączenia pojawi się błąd 401 (Brak autoryzacji) lub inna nieudana próba połączenia, błędu nie będzie można odzyskać, pobrany token zostanie odrzucony, a użytkownik będzie musiał ponownie zainicjować proces łączenia.HTTP/1.1 401 Unauthorized WWW-Authenticate: error="invalid_token", error_description="The Access Token expired"
Jeśli token dostępu jest prawidłowy, zwróć odpowiedź HTTP 200 z podanym niżej obiektem JSON w treści HTTPS odpowiedź:
Jeśli punkt końcowy informacji o użytkowniku zwraca odpowiedź HTTP 200, pobrany token i żądania są rejestrowane dla konta Google użytkownika.{ "sub": "USER_UUID", "email": "EMAIL_ADDRESS", "given_name": "FIRST_NAME", "family_name": "LAST_NAME", "name": "FULL_NAME", "picture": "PROFILE_PICTURE", }odpowiedź dotycząca punktu końcowego informacji o użytkowniku subUnikalny identyfikator, który identyfikuje użytkownika w Twoim systemie. emailAdres e-mail użytkownika. given_nameOpcjonalnie: imię użytkownika. family_nameOpcjonalnie: nazwisko użytkownika. nameOpcjonalnie: pełna nazwa użytkownika. pictureOpcjonalnie: zdjęcie profilowe użytkownika.
Sprawdzanie poprawności implementacji
You can validate your implementation by using the OAuth 2.0 Playground tool.
In the tool, do the following steps:
- Click Configuration to open the OAuth 2.0 Configuration window.
- In the OAuth flow field, select Client-side.
- In the OAuth Endpoints field, select Custom.
- Specify your OAuth 2.0 endpoint and the client ID you assigned to Google in the corresponding fields.
- In the Step 1 section, don't select any Google scopes. Instead, leave this field blank or type a scope valid for your server (or an arbitrary string if you don't use OAuth scopes). When you're done, click Authorize APIs.
- In the Step 2 and Step 3 sections, go through the OAuth 2.0 flow and verify that each step works as intended.
You can validate your implementation by using the Google Account Linking Demo tool.
In the tool, do the following steps:
- Click the Sign in with Google button.
- Choose the account you'd like to link.
- Enter the service ID.
- Optionally enter one or more scopes that you will request access for.
- Click Start Demo.
- When prompted, confirm that you may consent and deny the linking request.
- Confirm that you are redirected to your platform.