קישור חשבון Google באמצעות OAuth

הקישור בין החשבונות מתבצע באמצעות תהליך קוד ההרשאה של OAuth 2.0, שהוא תקן בתעשייה.

‫OAuth 2.1 ו-PKCE לסוכנים

מומלץ לאכוף את OAuth 2.1 עבור סוכני AI חסרי מצב ופייפליינים מולטי-מודאליים.

  • PKCE (מפתח אימות להחלפת קוד): חובה להשתמש בו כדי לאבטח את תהליך הרשאה באמצעות קוד ולמנוע מתקפות יירוט.
  • אין זרם הענקת גישה משתמע: זרם הענקת הגישה המשתמע חושף טוקני גישה בכתובת ה-URL, וזה סיכון אבטחה בסביבות של סוכנים.

השירות שלכם צריך לתמוך בנקודות קצה של הרשאה והחלפת טוקנים שתואמות ל-OAuth 2.0/2.1.

יצירת הפרויקט

כדי ליצור את הפרויקט לשימוש בקישור לחשבון:

  1. עוברים אל Google API Console.
  2. לוחצים על יצירת פרויקט.
  3. מזינים שם או מאשרים את ההצעה שנוצרה.
  4. מאשרים או עורכים את השדות שנותרו.
  5. לוחצים על יצירה.

כדי לראות את מזהה הפרויקט:

  1. עוברים אל Google API Console.
  2. מחפשים את הפרויקט בטבלה בדף הנחיתה. מזהה הפרויקט מופיע בעמודה ID.

תהליך קישור חשבון Google כולל מסך הסכמה שבו מוצגת למשתמש האפליקציה שמבקשת גישה לנתונים שלו, סוג הנתונים שהיא מבקשת והתנאים שחלים. תצטרכו להגדיר את מסך ההסכמה ל-OAuth לפני שתפיקו מזהה לקוח Google API.

  1. פותחים את הדף מסך ההסכמה ל-OAuth ב-Google APIs Console.
  2. אם מתבקשים, בוחרים את הפרויקט שיצרתם.
  3. בדף 'מסך ההסכמה ל-OAuth', ממלאים את הטופס ולוחצים על הלחצן 'שמירה'.

    שם האפליקציה: השם של האפליקציה שמבקשת הסכמה. השם צריך לשקף במדויק את האפליקציה שלכם ולהיות זהה לשם האפליקציה שמוצג למשתמשים במקומות אחרים. שם האפליקציה יוצג במסך ההסכמה לקישור החשבון.

    הלוגו של האפליקציה: תמונה במסך ההסכמה שתעזור למשתמשים לזהות את האפליקציה. הלוגו מוצג במסך ההסכמה לקישור החשבון ובהגדרות החשבון

    כתובת אימייל לתמיכה: כתובת אימייל שאליה משתמשים יכולים לפנות אם יש להם שאלות לגבי ההסכמה שלהם.

    היקפי גישה לממשקי Google API: היקפי גישה מאפשרים לאפליקציה לגשת לנתונים הפרטיים של המשתמשים ב-Google. במקרה השימוש של קישור לחשבון Google, היקף ברירת המחדל (אימייל, פרופיל, OpenID) מספיק, ואין צורך להוסיף היקפים רגישים. בדרך כלל מומלץ לבקש הרשאות בהדרגה, בזמן שנדרשת גישה, ולא מראש. מידע נוסף

    דומיינים מורשים: כדי להגן עליכם ועל המשתמשים שלכם, Google מאפשרת רק לאפליקציות שעוברות אימות באמצעות OAuth להשתמש בדומיינים מורשים. הקישורים לאפליקציות שלכם צריכים להיות מאוחסנים בדומיינים מורשים. מידע נוסף

    קישור לדף הבית של האפליקציה: דף הבית של האפליקציה. הן חייבות להתארח בדומיין מורשה.

    קישור למדיניות הפרטיות של האפליקציה: מוצג במסך ההסכמה לקישור לחשבון Google. הן חייבות להתארח בדומיין מורשה.

    קישור לתנאים ולהגבלות של האפליקציה (אופציונלי): הקישור צריך להיות מאוחסן בדומיין מורשה.

    איור 1. מסך הסכמה לקישור של חשבון Google לאפליקציה פיקטיבית, Tunery

  4. בודקים את 'סטטוס האימות'. אם האפליקציה שלכם צריכה אימות, לוחצים על הלחצן 'שליחה לאימות' כדי לשלוח את האפליקציה לאימות. פרטים נוספים מופיעים במאמר בנושא דרישות האימות של OAuth.

הטמעת שרת 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.

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).
טיפול בבקשות למידע על משתמשים

נקודת הקצה של userinfo היא משאב מוגן ב-OAuth 2.0 שמחזיר תלונות לגבי המשתמש המקושר. ההטמעה והאירוח של נקודת הקצה של userinfo הם אופציונליים, חוץ מאשר בתרחישים הבאים לדוגמה:

אחרי שהאחזור של אסימון הגישה מנקודת הקצה של האסימון מתבצע, Google שולחת בקשה לנקודת הקצה (endpoint) של userinfo כדי לאחזר פרטי פרופיל בסיסיים של המשתמש המקושר.

כותרות של בקשות של נקודות קצה של userinfo
Authorization header אסימון הגישה מסוג נושא.

לדוגמה, אם נקודת הקצה של Userinfo זמינה https://myservice.example.com/userinfo, בקשה עשויה להיראות כך:

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

כדי שנקודת הקצה של userinfo תטפל בבקשות, מבצעים את השלבים הבאים:

  1. מחלצים את אסימון הגישה מהכותרת Authorization ומחזירים מידע עבור המשתמש שמשויך לאסימון הגישה.
  2. אם אסימון הגישה לא חוקי, צריך להחזיר שגיאה מסוג HTTP 401 מאושר עם שימוש בכותרת התגובה WWW-Authenticate. דוגמה לתגובה עם שגיאה של userinfo:
    HTTP/1.1 401 Unauthorized
    WWW-Authenticate: error="invalid_token",
    error_description="The Access Token expired"
    
    אם מתקבלת תגובה מסוג '401' ללא הרשאה, או כל תגובה אחרת של שגיאה שנכשלה במהלך תהליך הקישור, לא ניתן לשחזר את השגיאה, האסימון שאוחזר יימחק והמשתמש יצטרך להתחיל מחדש את תהליך הקישור.
  3. אם אסימון הגישה תקין, מוחזר ותגובת HTTP 200 עם אובייקט ה-JSON הבא בגוף ה-HTTPS תגובה:

    {
    "sub": "USER_UUID",
    "email": "EMAIL_ADDRESS",
    "given_name": "FIRST_NAME",
    "family_name": "LAST_NAME",
    "name": "FULL_NAME",
    "picture": "PROFILE_PICTURE",
    }
    אם נקודת הקצה (endpoint) של userinfo מחזירה תגובה מוצלחת מסוג HTTP 200, האסימון שאוחזר וההצהרות על זכויות יוצרים יירשמו בחשבון Google של המשתמש.

    תגובה של נקודת הקצה של userinfo
    sub מזהה ייחודי שמזהה את המשתמש במערכת שלכם.
    email כתובת האימייל של המשתמש.
    given_name אופציונלי: השם הפרטי של המשתמש.
    family_name אופציונלי: שם המשפחה של המשתמש.
    name אופציונלי: השם המלא של המשתמש.
    picture אופציונלי: תמונת פרופיל של המשתמש.

אימות ההטמעה

כדי לאמת את ההטמעה, אפשר להשתמש בכלי OAuth 2.0 Playground.

בכלי, מבצעים את השלבים הבאים:

  1. לוחצים על Configuration (הגדרה) כדי לפתוח את חלון ההגדרה של OAuth 2.0.
  2. בשדה OAuth flow (תהליך OAuth), בוחרים באפשרות Client-side (בצד הלקוח).
  3. בשדה OAuth Endpoints (נקודות קצה של OAuth), בוחרים באפשרות Custom (מותאם אישית).
  4. בשדות המתאימים, מציינים את נקודת הקצה של OAuth 2.0 ואת מזהה הלקוח שהקציתם ל-Google.
  5. בקטע Step 1, לא בוחרים אף היקף של Google. במקום זאת, משאירים את השדה הזה ריק או מקלידים היקף הרשאות שתקף לשרת (או מחרוזת שרירותית אם לא משתמשים בהיקפי הרשאות OAuth). בסיום, לוחצים על הרשאת ממשקי API.
  6. בקטעים שלב 2 ושלב 3, עוברים על תהליך ההרשאה באמצעות OAuth 2.0 ומוודאים שכל שלב פועל כמו שצריך.

כדי לאמת את ההטמעה, אפשר להשתמש בכלי Google Account Linking Demo.

בכלי, מבצעים את השלבים הבאים:

  1. לוחצים על הכפתור כניסה באמצעות חשבון Google.
  2. בוחרים את החשבון שרוצים לקשר.
  3. מזינים את מזהה השירות.
  4. אפשר להזין היקף אחד או יותר שרוצים לבקש גישה אליהם.
  5. לוחצים על התחלת ההדגמה.
  6. כשמופיעה הבקשה, מאשרים שרוצים להסכים לבקשת הקישור או לדחות אותה.
  7. מוודאים שמופנים לפלטפורמה שלכם.