כשמשתמשים ב-Google Identity Services או בתהליך קוד ההרשאה של OAuth 2.0, Google מחזירה את אסימון הזהות באמצעות שיטת POST לנקודת הקצה של ההפניה האוטומטית. לחלופין, בתהליך המשתמע של OIDC נעשה שימוש בבקשת GET. לכן, האפליקציה שלכם אחראית להעביר את פרטי הכניסה האלה לשרת בצורה מאובטחת.
זהו זרם הענקת גישה משתמע, האסימון המזהה מוחזר בתוך קטע כתובת ה-URL, שצריך לנתח באמצעות JavaScript בצד הלקוח. האפליקציה שלכם אחראית להטמעת מנגנוני אימות משלה כדי לוודא שהבקשה אותנטית ולמנוע התקפות כמו CSRF.
HTTP/1.1 302 Found Location: https://<REDIRECT_URI>#access_token=<ACCESS_TOKEN>&token_type=bearer&expires_in=<TIME_IN_SECONDS>&scope=<SCOPE>&state=<STATE_STRING>
טוקן המזהה נשלח חזרה כשדה credential. בזמן ההכנה לשליחת האסימון המזהה לשרת, ספריית GIS מוסיפה באופן אוטומטי את g_csrf_token לקובץ ה-Cookie של הכותרת ולגוף הבקשה. דוגמה לבקשת POST:
POST /auth/token-verification HTTP/1.1 Host: example.com Content-Type: application/json;charset=UTF-8 Cookie: g_csrf_token=<CSRF_TOKEN> Origin: https://example.com Content-Length: <LENGTH_OF_JSON_BODY> { "credential": "<ID_TOKEN>", "g_csrf_token": "<CSRF_TOKEN>", "client_id": "<CLIENT_ID>" }
אימות של
g_csrf_tokenכדי למנוע מתקפות של זיוף בקשות חוצה-אתרים (CSRF):- מחפשים את הערך של אסימון ה-CSRF בקובץ ה-Cookie
g_csrf_token. - מחפשים את הערך של אסימון ה-CSRF בגוף הבקשה. ספריית GIS כוללת את האסימון הזה בגוף בקשת ה-POST כפרמטר, שנקרא גם
g_csrf_token. - השוואה בין שני ערכי טוקן
- אם שני הערכים קיימים ותואמים לחלוטין, הבקשה נחשבת ללגיטימית ומקורה בדומיין שלכם.
- אם הערכים לא קיימים או לא תואמים, השרת צריך לדחות את הבקשה.
בבדיקה הזו מוודאים שהבקשה נוצרה מ-JavaScript שפועל בדומיין שלכם, כי רק לדומיין שלכם יש גישה לקובץ ה-Cookie
g_csrf_token.
- מחפשים את הערך של אסימון ה-CSRF בקובץ ה-Cookie
מאמתים את האסימון המזהה.
כדי לוודא שהאסימון תקין, צריך לוודא שהקריטריונים הבאים מתקיימים:
- טוקן המזהה חתום בצורה תקינה על ידי Google. משתמשים במפתחות הציבוריים של Google (זמינים בפורמט JWK או PEM) כדי לאמת את חתימת האסימון. המפתחות האלה מתחלפים באופן קבוע. כדי לדעת מתי צריך לאחזר אותם שוב, צריך לבדוק את הכותרת
Cache-Controlבתשובה. - הערך של
audבטוקן ה-ID שווה לאחד ממזהי הלקוח של האפליקציה. הבדיקה הזו נחוצה כדי למנוע שימוש באסימונים מזהים שהונפקו לאפליקציה זדונית כדי לגשת לנתונים על אותו משתמש בשרת העורפי של האפליקציה שלכם. - הערך של
issבטוקן המזהה שווה ל-accounts.google.comאו ל-https://accounts.google.com. - תאריך התפוגה (
exp) של טוקן המזהה עוד לא חלף. - אם אתם צריכים לוודא שטוקן ה-ID מייצג חשבון ארגוני ב-Google Workspace או ב-Cloud, אתם יכולים לבדוק את טענת
hd, שמציינת את הדומיין המארח של המשתמש. חובה להשתמש בהגדרה הזו כשרוצים להגביל את הגישה למשאב רק לחברים בדומיינים מסוימים. אם התביעה הזו לא מופיעה, סימן שהחשבון לא שייך לדומיין שמארח את Google.
באמצעות השדות
email,email_verifiedו-hd, אפשר לקבוע אם Google מארחת כתובת אימייל ומוגדרת כסמכותית לגביה. במקרים שבהם Google היא הסמכות, המשתמש מזוהה כבעל החשבון הלגיטימי, ואפשר לדלג על הסיסמה או על שיטות אחרות לאימות.מקרים שבהם Google היא הסמכות:
-
emailיש סיומת@gmail.com, זה חשבון Gmail. -
email_verifiedנכון ו-hdמוגדר, זהו חשבון Google Workspace.
משתמשים יכולים להירשם לחשבונות Google בלי להשתמש ב-Gmail או ב-Google Workspace. אם
emailלא מכיל את הסיומת@gmail.comו-hdלא מופיע, Google לא מהימנה ומומלץ להשתמש בסיסמה או בשיטות אחרות לאימות כדי לאמת את המשתמש. יכול להיות שגםemail_verifiedנכון, כי Google אימתה את המשתמש בהתחלה כשחשבון Google נוצר, אבל יכול להיות שהבעלות על חשבון האימייל של הצד השלישי השתנתה מאז.במקום לכתוב קוד משלכם כדי לבצע את שלבי האימות האלה, מומלץ מאוד להשתמש בספריית לקוח של Google API עבור הפלטפורמה שלכם, או בספריית JWT למטרות כלליות. למטרות פיתוח וניפוי באגים, אפשר להתקשר אל נקודת הקצה שלנו לאימות
tokeninfo.Using a Google API Client Library
Using one of the Google API Client Libraries (e.g. Java, Node.js, PHP, Python) is the recommended way to validate Google ID tokens in a production environment.
Java To validate an ID token in Java, use the GoogleIdTokenVerifier object. For example:
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload; import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; ... GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory) // Specify the WEB_CLIENT_ID of the app that accesses the backend: .setAudience(Collections.singletonList(WEB_CLIENT_ID)) // Or, if multiple clients access the backend: //.setAudience(Arrays.asList(WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3)) .build(); // (Receive idTokenString by HTTPS POST) GoogleIdToken idToken = verifier.verify(idTokenString); if (idToken != null) { Payload payload = idToken.getPayload(); // Print user identifier. This ID is unique to each Google Account, making it suitable for // use as a primary key during account lookup. Email is not a good choice because it can be // changed by the user. String userId = payload.getSubject(); System.out.println("User ID: " + userId); // Get profile information from payload String email = payload.getEmail(); boolean emailVerified = Boolean.valueOf(payload.getEmailVerified()); String name = (String) payload.get("name"); String pictureUrl = (String) payload.get("picture"); String locale = (String) payload.get("locale"); String familyName = (String) payload.get("family_name"); String givenName = (String) payload.get("given_name"); // Use or store profile information // ... } else { System.out.println("Invalid ID token."); }
The
GoogleIdTokenVerifier.verify()method verifies the JWT signature, theaudclaim, theissclaim, and theexpclaim.If you need to validate that the ID token represents a Google Workspace or Cloud organization account, you can verify the
hdclaim by checking the domain name returned by thePayload.getHostedDomain()method. The domain of theemailclaim is insufficient to ensure that the account is managed by a domain or organization.Node.js To validate an ID token in Node.js, use the Google Auth Library for Node.js. Install the library:
Then, call thenpm install google-auth-library --save
verifyIdToken()function. For example:const {OAuth2Client} = require('google-auth-library'); const client = new OAuth2Client(); async function verify() { const ticket = await client.verifyIdToken({ idToken: token, audience: WEB_CLIENT_ID, // Specify the WEB_CLIENT_ID of the app that accesses the backend // Or, if multiple clients access the backend: //[WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3] }); const payload = ticket.getPayload(); // This ID is unique to each Google Account, making it suitable for use as a primary key // during account lookup. Email is not a good choice because it can be changed by the user. const userid = payload['sub']; // If the request specified a Google Workspace domain: // const domain = payload['hd']; } verify().catch(console.error);
The
verifyIdTokenfunction verifies the JWT signature, theaudclaim, theexpclaim, and theissclaim.If you need to validate that the ID token represents a Google Workspace or Cloud organization account, you can check the
hdclaim, which indicates the hosted domain of the user. This must be used when restricting access to a resource to only members of certain domains. The absence of this claim indicates that the account does not belong to a Google hosted domain.PHP To validate an ID token in PHP, use the Google API Client Library for PHP. Install the library (for example, using Composer):
Then, call thecomposer require google/apiclient
verifyIdToken()function. For example:require_once 'vendor/autoload.php'; // Get $id_token via HTTPS POST. $client = new Google_Client(['client_id' => $WEB_CLIENT_ID]); // Specify the WEB_CLIENT_ID of the app that accesses the backend $payload = $client->verifyIdToken($id_token); if ($payload) { // This ID is unique to each Google Account, making it suitable for use as a primary key // during account lookup. Email is not a good choice because it can be changed by the user. $userid = $payload['sub']; // If the request specified a Google Workspace domain //$domain = $payload['hd']; } else { // Invalid ID token }
The
verifyIdTokenfunction verifies the JWT signature, theaudclaim, theexpclaim, and theissclaim.If you need to validate that the ID token represents a Google Workspace or Cloud organization account, you can check the
hdclaim, which indicates the hosted domain of the user. This must be used when restricting access to a resource to only members of certain domains. The absence of this claim indicates that the account does not belong to a Google hosted domain.Python To validate an ID token in Python, use the verify_oauth2_token function. For example:
from google.oauth2 import id_token from google.auth.transport import requests # (Receive token by HTTPS POST) # ... try: # Specify the WEB_CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token, requests.Request(), WEB_CLIENT_ID) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3]: # raise ValueError('Could not verify audience.') # If the request specified a Google Workspace domain # if idinfo['hd'] != DOMAIN_NAME: # raise ValueError('Wrong domain name.') # ID token is valid. Get the user's Google Account ID from the decoded token. # This ID is unique to each Google Account, making it suitable for use as a primary key # during account lookup. Email is not a good choice because it can be changed by the user. userid = idinfo['sub'] except ValueError: # Invalid token pass
The
verify_oauth2_tokenfunction verifies the JWT signature, theaudclaim, and theexpclaim. You must also verify thehdclaim (if applicable) by examining the object thatverify_oauth2_tokenreturns. If multiple clients access the backend server, also manually verify theaudclaim.- טוקן המזהה חתום בצורה תקינה על ידי Google. משתמשים במפתחות הציבוריים של Google (זמינים בפורמט JWK או PEM) כדי לאמת את חתימת האסימון. המפתחות האלה מתחלפים באופן קבוע. כדי לדעת מתי צריך לאחזר אותם שוב, צריך לבדוק את הכותרת
אחרי שמאשרים את התוקף של הטוקן, אפשר להשתמש במידע בטוקן של מזהה Google כדי לקשר בין סטטוס החשבון באתר שלכם:
משתמש לא רשום: אתם יכולים להציג ממשק משתמש להרשמה שמאפשר למשתמש לספק מידע נוסף לפרופיל, אם נדרש. היא גם מאפשרת למשתמש ליצור בשקט את החשבון החדש ואת סשן המשתמש המחובר.
חשבון קיים שכבר קיים באתר שלכם: אתם יכולים להציג דף אינטרנט שמאפשר למשתמש הקצה להזין את הסיסמה שלו ולקשר את החשבון מדור קודם לפרטי הכניסה שלו לחשבון Google. כך נוכל לוודא שלמשתמש יש גישה לחשבון הקיים.
משתמש מאוחד שחוזר: אתם יכולים להכניס את המשתמש לחשבון באופן שקוף.