ربط حساب Google باستخدام OAuth

يتم ربط الحسابات باستخدام مسار رمز التفويض المتوافق مع معيار OAuth 2.0 المتّبع في المجال.

بروتوكول OAuth 2.1 وPKCE للوكلاء

بالنسبة إلى وكلاء الذكاء الاصطناعي غير الاحتفاظي الحالة ومسارات العرض المتعدّد، يُنصح بفرض استخدام OAuth 2.1.

  • مفتاح الحماية لتبادل الرموز (PKCE): يجب استخدامه لتأمين مسار رمز التفويض، ما يمنع هجمات الاعتراض.
  • بدون تدفق ضمني: يعرض التدفق الضمني رموز الدخول في عنوان URL، ما يشكّل خطرًا أمنيًا على بيئات الوكيل.

يجب أن تتيح خدمتك نقاط نهاية الترخيص وتبادل الرموز المميزة المتوافقة مع OAuth 2.0/2.1.

إنشاء المشروع

لإنشاء مشروعك لاستخدام ميزة ربط الحسابات، اتّبِع الخطوات التالية:

  1. انتقِل إلى وحدة التحكم في واجهة Google API.
  2. انقر على إنشاء مشروع.
  3. أدخِل اسمًا أو اقبل الاقتراح الذي تم إنشاؤه.
  4. أكِّد أي حقول متبقية أو عدِّلها.
  5. انقر على إنشاء.

للاطّلاع على رقم تعريف مشروعك، اتّبِع الخطوات التالية:

  1. انتقِل إلى وحدة التحكم في واجهة Google API.
  2. ابحث عن مشروعك في الجدول على الصفحة المقصودة. يظهر رقم تعريف المشروع في العمود المعرّف.

تتضمّن عملية ربط حساب Google شاشة طلب الموافقة التي تُطلع المستخدمين على التطبيق الذي يطلب الوصول إلى بياناتهم، ونوع البيانات التي يطلبها، والبنود السارية. عليك ضبط شاشة طلب الموافقة المتعلّقة ببروتوكول OAuth قبل إنشاء معرّف عميل لواجهة Google API.

  1. افتح صفحة شاشة طلب الموافقة المتعلّقة ببروتوكول OAuth في وحدة تحكّم Google APIs.
  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 طلبًا إلى نقطة نهاية معلومات المستخدم لاسترداد معلومات الملف الشخصي الأساسية عن المستخدم المرتبط.

عناوين طلبات نقطة نهاية userinfo
Authorization header رمز الدخول من النوع "الحامل".

على سبيل المثال، إذا كانت نقطة نهاية userinfo متاحة على https://myservice.example.com/userinfo، قد يظهر الطلب على النحو التالي:

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

لتتمكّن نقطة نهاية معلومات المستخدم من معالجة الطلبات، عليك اتّباع الخطوات التالية:

  1. يمكنك استخراج رمز الدخول من عنوان التفويض ومعلومات الإرجاع للمستخدم المرتبط برمز الدخول.
  2. إذا كان رمز الدخول غير صالح، يمكنك عرض الخطأ HTTP 401 "غير مصرح به" مع استخدام عنوان الاستجابة WWW-Authenticate. في ما يلي مثال على استجابة خطأ في معلومات المستخدم:
    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",
    }
    إذا عرضت نقطة نهاية معلومات المستخدم استجابة نجاح HTTP 200، يتم تسجيل الرمز المميز الذي تم استرداده والمطالبات مقابل حساب المستخدم على Google.

    استجابة نقطة نهاية لمعلومات المستخدم
    sub معرّف فريد يعرّف المستخدِم في نظامك.
    email عنوان البريد الإلكتروني للمستخدم.
    given_name اختياري: الاسم الأول للمستخدم.
    family_name اختياري: اسم العائلة للمستخدم.
    name اختياري: اسم المستخدم الكامل.
    picture اختياري: صورة الملف الشخصي للمستخدم.

التحقّق من صحة عملية التنفيذ

يمكنك التحقّق من صحة التنفيذ باستخدام أداة مساحة بروتوكول OAuth 2.0.

في الأداة، اتّبِع الخطوات التالية:

  1. انقر على الإعداد لفتح نافذة "إعدادات OAuth 2.0".
  2. في حقل مسار OAuth، اختَر من جهة العميل.
  3. في حقل نقاط نهاية OAuth، اختَر مخصّص.
  4. حدِّد نقطة نهاية OAuth 2.0 ومعرّف العميل الذي خصّصته لـ Google في الحقلَين المناسبَين.
  5. في قسم الخطوة 1، لا تحدّد أي نطاقات Google. بدلاً من ذلك، اترك هذا الحقل فارغًا أو اكتب نطاقًا صالحًا لخادمك (أو سلسلة عشوائية إذا كنت لا تستخدم نطاقات OAuth). عند الانتهاء، انقر على تفويض واجهات برمجة التطبيقات.
  6. في القسمَين الخطوة 2 والخطوة 3، اتّبِع مسار OAuth 2.0 وتأكَّد من أنّ كل خطوة تعمل على النحو المطلوب.

يمكنك التحقّق من صحة عملية التنفيذ باستخدام أداة عرض توضيحي لربط حساب Google.

في الأداة، اتّبِع الخطوات التالية:

  1. انقر على الزر تسجيل الدخول باستخدام حساب Google.
  2. اختَر الحساب الذي تريد ربطه.
  3. أدخِل رقم تعريف الخدمة.
  4. يمكنك اختياريًا إدخال نطاق واحد أو أكثر ستطلب الوصول إليه.
  5. انقر على بدء العرض التوضيحي.
  6. أكِّد أنّه يمكنك الموافقة على طلب ربط الحساب ورفضه عندما يُطلب منك ذلك.
  7. تأكَّد من إعادة توجيهك إلى منصتك.