Google-Kontoverknüpfung mit OAuth

Konten werden über den Branchenstandard-OAuth 2.0-Vorgang mit Autorisierungscode verknüpft.

OAuth 2.1 und PKCE für Agents

Für zustandslose KI-Agents und multimodale Pipelines wird die OAuth 2.1-Durchsetzung empfohlen.

  • PKCE (Proof Key for Code Exchange): Muss verwendet werden, um den Autorisierungscode-Vorgang zu schützen und Abfangangriffe zu verhindern.
  • Kein impliziter Ablauf: Beim impliziten Ablauf werden Zugriffstokens in der URL verfügbar gemacht, was ein Sicherheitsrisiko für Agent-Umgebungen darstellt.

Ihr Dienst muss OAuth 2.0-/2.1-konforme Autorisierungs- und Tokenaustausch-Endpunkte unterstützen.

Projekt erstellen

So erstellen Sie Ihr Projekt für die Kontoverknüpfung:

  1. Gehen Sie zur Google API Console.
  2. Klicken Sie auf Projekt erstellen.
  3. Geben Sie einen Namen ein oder übernehmen Sie den generierten Vorschlag.
  4. Bestätigen oder bearbeiten Sie die verbleibenden Felder.
  5. Klicken Sie auf Erstellen.

So rufen Sie Ihre Projekt-ID auf:

  1. Gehen Sie zur Google API Console.
  2. Suchen Sie in der Tabelle auf der Landingpage nach Ihrem Projekt. Die Projekt-ID wird in der Spalte ID angezeigt.

Der Prozess zur Verknüpfung von Google-Konten umfasst einen Zustimmungsbildschirm, auf dem Nutzer darüber informiert werden, welche Anwendung Zugriff auf ihre Daten anfordert, welche Art von Daten angefordert werden und welche Nutzungsbedingungen gelten. Sie müssen den OAuth-Zustimmungsbildschirm konfigurieren, bevor Sie eine Google API-Client-ID generieren.

  1. Öffnen Sie in der Google APIs Console die Seite OAuth-Zustimmungsbildschirm.
  2. Wählen Sie bei Aufforderung das Projekt aus, das Sie gerade erstellt haben.
  3. Füllen Sie auf der Seite „OAuth-Zustimmungsbildschirm“ das Formular aus und klicken Sie auf die Schaltfläche „Speichern“.

    Anwendungsname:Der Name der Anwendung, die um Einwilligung bittet. Der Name sollte Ihre Anwendung korrekt widerspiegeln und mit dem Anwendungsnamen übereinstimmen, den Nutzer an anderer Stelle sehen. Der Anwendungsname wird auf dem Zustimmungsbildschirm für die Kontoverknüpfung angezeigt.

    App-Logo:Ein Bild auf dem Zustimmungsbildschirm, das Nutzern hilft, Ihre App zu erkennen. Das Logo wird auf dem Zustimmungsbildschirm für die Kontoverknüpfung und in den Kontoeinstellungen angezeigt.

    Support-E-Mail-Adresse:Für Nutzer, die Sie wegen Fragen zu ihrer Einwilligung kontaktieren möchten.

    Bereiche für Google-APIs:Mit Bereichen kann Ihre Anwendung auf die privaten Google-Daten Ihrer Nutzer zugreifen. Für die Verknüpfung von Google-Konten reicht der Standardbereich („email“, „profile“, „openid“) aus. Sie müssen keine sensiblen Bereiche hinzufügen. Es empfiehlt sich, Bereiche inkrementell anzufordern, wenn der Zugriff erforderlich ist, und nicht im Voraus. Weitere Informationen

    Autorisierte Domains:Um Sie und Ihre Nutzer zu schützen, erlaubt Google die Nutzung autorisierter Domains nur Anwendungen, die sich mit OAuth authentifizieren. Die Links Ihrer Anwendungen müssen auf autorisierten Domains gehostet werden. Weitere Informationen

    Link zur Startseite der Anwendung:Startseite Ihrer Anwendung. Muss auf einer autorisierten Domain gehostet werden.

    Link zur Datenschutzerklärung der Anwendung:Wird auf dem Zustimmungsbildschirm für die Verknüpfung von Google-Konten angezeigt. Muss auf einer autorisierten Domain gehostet werden.

    Link zu den Nutzungsbedingungen der Anwendung (optional): Muss auf einer autorisierten Domain gehostet werden.

    Abbildung 1. Zustimmungsbildschirm für die Google-Kontoverknüpfung für die fiktive App „Tunery“

  4. Prüfen Sie den „Überprüfungsstatus“. Wenn Ihre Anwendung überprüft werden muss, klicken Sie auf die Schaltfläche „Zur Überprüfung einreichen“, um sie zur Überprüfung einzureichen. Weitere Informationen finden Sie unter Voraussetzungen für die OAuth-Überprüfung.

OAuth-Server implementieren

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.

User Google App / Browser Google Server Your Auth Endpoint Your Token Endpoint 1. User initiates linking 2. Redirect to Auth Endpoint (GET) client_id, redirect_uri, state, scope 3. Display Sign-in & Consent Screen 4. User Authenticates & Grants Consent 5. Redirect back to Google (GET) code, state 6. Handle redirect & pass code/state 7. Token Exchange (POST) grant_type=authorization_code, code 8. Return Tokens (200 OK) access_token, refresh_token 9. Store user tokens 10. Access user resources
Figure 1. The sequence of events in the OAuth 2.0 Authorization Code flow for Google Account Linking.

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:

  1. 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.
  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. To do so, redirect 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 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:

  1. Validate the request:

    • Confirm that the client_id matches the Client ID assigned to Google.
    • Confirm that the redirect_uri matches 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_type is code.
  2. 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.
  3. 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.
  4. 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.

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.

  1. Validate the request:

    • Verify client_id and client_secret.
    • Verify the authorization code is valid and not expired.
    • Confirm redirect_uri matches the value used in Step 1.
    • If validation fails, return an HTTP 400 Bad Request with {"error": "invalid_grant"}.
  2. Issue tokens:

    • Generate a long-lived refresh_token and a short-lived access_token (typically 1 hour).
    • Return an HTTP 200 OK with the standard JSON token response.

B. Refresh access tokens

When the access token expires, Google requests a new one using the refresh token.

  1. Validate the request:

    • Verify client_id, client_secret, and refresh_token.
    • If validation fails, return an HTTP 400 Bad Request with {"error": "invalid_grant"}.
  2. Issue new access token:

    • Generate a new short-lived access_token.
    • Return an HTTP 200 OK with the JSON token response (optionally including a new refresh token).
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:

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:

  1. Extract access token from the Authorization header and return information for the user associated with the access token.
  2. If the access token is invalid, return an HTTP 401 Unauthorized error with using the WWW-Authenticate Response Header. Below is an example of a userinfo error response:
    HTTP/1.1 401 Unauthorized
    WWW-Authenticate: error="invalid_token",
    error_description="The Access Token expired"
    
    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.
  3. If the access token is valid, return and HTTP 200 response with the following JSON object in the body of the HTTPS response:

    {
    "sub": "USER_UUID",
    "email": "EMAIL_ADDRESS",
    "given_name": "FIRST_NAME",
    "family_name": "LAST_NAME",
    "name": "FULL_NAME",
    "picture": "PROFILE_PICTURE",
    }
    If your userinfo endpoint returns an HTTP 200 success response, the retrieved token and claims are registered against the user's Google account.

    userinfo endpoint response
    sub A unique ID that identifies the user in your system.
    email Email address of the user.
    given_name Optional: First name of the user.
    family_name Optional: Last name of the user.
    name Optional: Full name of the user.
    picture Optional: Profile picture of the user.

Implementierung validieren

Sie können Ihre Implementierung mit dem OAuth 2.0 Playground Tool validieren.

Führen Sie im Tool die folgenden Schritte aus:

  1. Klicken Sie auf die Konfigurationseinstellungen , um das Fenster „OAuth 2.0-Konfiguration“ zu öffnen.
  2. Wählen Sie im Feld OAuth-Ablauf die Option Clientseitig aus.
  3. Wählen Sie im Feld OAuth-Endpunkte die Option Benutzerdefiniert aus.
  4. Geben Sie in den entsprechenden Feldern Ihren OAuth 2.0-Endpunkt und die Client-ID an, die Sie Google zugewiesen haben.
  5. Wählen Sie im Abschnitt Schritt 1 keine Google-Bereiche aus. Lassen Sie dieses Feld stattdessen leer oder geben Sie einen für Ihren Server gültigen Bereich ein (oder eine beliebige Zeichenfolge, wenn Sie keine OAuth-Bereiche verwenden). Klicken Sie anschließend auf APIs autorisieren.
  6. Führen Sie in den Abschnitten Schritt 2 und Schritt 3 den OAuth 2.0-Ablauf durch und prüfen Sie, ob jeder Schritt wie vorgesehen funktioniert.

Sie können Ihre Implementierung mit dem Tool „Google-Kontoverknüpfung – Demo“ validieren.

Führen Sie im Tool die folgenden Schritte aus:

  1. Klicken Sie auf die Schaltfläche Mit Google anmelden.
  2. Wählen Sie das Konto aus, das Sie verknüpfen möchten.
  3. Geben Sie die Dienst-ID ein.
  4. Optional können Sie einen oder mehrere Bereiche eingeben, für die Sie Zugriff anfordern möchten.
  5. Klicken Sie auf Demo starten.
  6. Bestätigen Sie bei Aufforderung, dass Sie der Verknüpfungsanfrage zustimmen und sie ablehnen können.
  7. Bestätigen Sie, dass Sie zu Ihrer Plattform weitergeleitet werden.