קבלת אסימוני הרשאה
קל לארגן דפים בעזרת אוספים
אפשר לשמור ולסווג תוכן על סמך ההעדפות שלך.
מה זה טוקן?
ב-Fleet Engine נדרש שימוש באסימוני JWT (JSON Web Tokens) לקריאות ל-API method מסביבות עם רמת אבטחה נמוכה: סמארטפונים ודפדפנים.
אסימון JWT נוצר בשרת שלכם, נחתם, מוצפן ומועבר ללקוח לאינטראקציות הבאות עם השרת עד שהוא פג או עד שהוא כבר לא תקף.
פרטים חשובים
למידע נוסף על אסימוני JWT, אפשר לעיין במאמר אסימוני JWT במאמרים בנושא Fleet Engine.
איך לקוחות מקבלים אסימונים?
אחרי שבעל מונית או לקוח מתחברים לאפליקציה באמצעות פרטי ההרשאה המתאימים, כל עדכון שיוצא מהמכשיר הזה חייב להשתמש באסימוני הרשאה מתאימים, שמעבירים ל-Fleet Engine את ההרשאות של האפליקציה.
המפתח צריך להטמיע את הלקוח כך שיהיה אפשר לבצע את הפעולות הבאות:
- מאחזרים אסימון JWT מהשרת.
- כדי לצמצם את מספר הפעמים שבהן צריך לרענן את הטוקן, אפשר להשתמש בו שוב ושוב עד שתוקף שלו יפוג.
- מרעננים את הטוקן כשהתוקף שלו פג.
המחלקות AuthTokenFactory
יוצרות טוקנים של הרשאה בזמן עדכון המיקום. ערכת ה-SDK צריכה לארוז את האסימונים עם פרטי העדכון כדי לשלוח אותם ל-Fleet Engine. לפני שמפעילים את ה-SDK, צריך לוודא שההטמעה בצד השרת יכולה להנפיק טוקנים.
פרטים על האסימונים ששירות Fleet Engine מצפה להם מופיעים במאמר יצירת אסימוני אינטרנט מסוג JSON עבור Fleet Engine.
דוגמה ל-fetcher של טוקן הרשאה
הנה הטמעה בסיסית של AuthTokenFactory
:
class JsonAuthTokenFactory implements AuthTokenFactory {
private String vehicleServiceToken; // initially null
private long expiryTimeMs = 0;
private String vehicleId;
// This method is called on a thread whose only responsibility is to send
// location updates. Blocking is OK, but just know that no location updates
// can occur until this method returns.
@Override
public String getToken(AuthTokenContext authTokenContext) {
String vehicleId = requireNonNull(context.getVehicleId());
if (System.currentTimeMillis() > expiryTimeMs || !vehicleId.equals(this.vehicleId)) {
// The token has expired, go get a new one.
fetchNewToken(vehicleId);
}
return vehicleServiceToken;
}
private void fetchNewToken(String vehicleId) {
String url = "https://yourauthserver.example/token/" + vehicleId;
try (Reader r = new InputStreamReader(new URL(url).openStream())) {
com.google.gson.JsonObject obj
= com.google.gson.JsonParser.parseReader(r).getAsJsonObject();
vehicleServiceToken = obj.get("VehicleServiceToken").getAsString();
expiryTimeMs = obj.get("TokenExpiryMs").getAsLong();
// The expiry time could be an hour from now, but just to try and avoid
// passing expired tokens, we subtract 10 minutes from that time.
expiryTimeMs -= 10 * 60 * 1000;
this.vehicleId = vehicleId;
} catch (IOException e) {
// It's OK to throw exceptions here. The StatusListener you passed to
// create the DriverContext class will be notified and passed along the failed
// update warning.
throw new RuntimeException("Could not get auth token", e);
}
}
}
ההטמעה הספציפית הזו משתמשת בלקוח ה-HTTP המובנה של Java כדי לאחזר אסימון בפורמט JSON משרת ההרשאות. הלקוח שומר את האסימון לשימוש חוזר ומאחזר אותו מחדש אם התוקף של האסימון הישן עומד לפוג תוך 10 דקות.
יכול להיות שההטמעה שלכם תפעל בצורה שונה, למשל באמצעות שרשור ברקע לרענון טוקנים.
במאמר ספריות לקוח לשירותים של נסיעות על פי דרישה מפורטות ספריות הלקוח שזמינות ל-Fleet Engine.
המאמרים הבאים
אתחול Driver SDK
אלא אם צוין אחרת, התוכן של דף זה הוא ברישיון Creative Commons Attribution 4.0 ודוגמאות הקוד הן ברישיון Apache 2.0. לפרטים, ניתן לעיין במדיניות האתר Google Developers. Java הוא סימן מסחרי רשום של חברת Oracle ו/או של השותפים העצמאיים שלה.
עדכון אחרון: 2025-09-05 (שעון UTC).
[[["התוכן קל להבנה","easyToUnderstand","thumb-up"],["התוכן עזר לי לפתור בעיה","solvedMyProblem","thumb-up"],["סיבה אחרת","otherUp","thumb-up"]],[["חסרים לי מידע או פרטים","missingTheInformationINeed","thumb-down"],["התוכן מורכב מדי או עם יותר מדי שלבים","tooComplicatedTooManySteps","thumb-down"],["התוכן לא עדכני","outOfDate","thumb-down"],["בעיה בתרגום","translationIssue","thumb-down"],["בעיה בדוגמאות/בקוד","samplesCodeIssue","thumb-down"],["סיבה אחרת","otherDown","thumb-down"]],["עדכון אחרון: 2025-09-05 (שעון UTC)."],[[["\u003cp\u003eFleet Engine utilizes JSON Web Tokens (JWTs) for API method calls originating from low-trust environments like smartphones and browsers, requiring these tokens to be signed by an appropriate service account on your server.\u003c/p\u003e\n"],["\u003cp\u003eClients, after logging in, must employ authorization tokens for updates, which are fetched from your server, reused until expiration, and then refreshed to maintain communication with Fleet Engine.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eAuthTokenFactory\u003c/code\u003e class generates authorization tokens for location updates, which are then packaged with the update information by the SDK and sent to Fleet Engine, requiring a server-side implementation for token issuance.\u003c/p\u003e\n"],["\u003cp\u003eAn example \u003ccode\u003eAuthTokenFactory\u003c/code\u003e implementation demonstrates fetching tokens in JSON format from an authorization server, saving them for reuse, and refreshing them within 10 minutes of expiry to ensure continuous authorization.\u003c/p\u003e\n"]]],[],null,["What is a token?\n\nFleet Engine requires the use of **JSON Web Tokens** (JWTs) for API method calls\nfrom **low-trust environments**: smartphones and browsers.\n\nA JWT originates on your server, is signed, encrypted, and passed to the client\nfor subsequent server interactions until it expires or is no longer valid.\n\n**Key details**\n\n- Use [Application Default Credentials](https://google.aip.dev/auth/4110) to authenticate and authorize against Fleet Engine.\n- Use an appropriate service account to sign JWTs. See [Fleet Engine serviceaccount](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/service-accounts#fleet_engine_service_account_roles) roles in **Fleet Engine Basics**.\n\nFor more information about JSON Web Tokens, see [JSON Web Tokens](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/jwt) in\n**Fleet Engine Essentials**.\n\nHow do clients get tokens?\n\nOnce a driver or consumer logs in to your app using the appropriate\nauthorization credentials, any updates issued from that device must use\nappropriate authorization tokens, which communicates to Fleet Engine the\npermissions for the app.\n\nAs the developer, your client implementation should provide the ability to do\nthe following:\n\n- Fetch a JSON Web Token from your server.\n- Reuse the token until it expires to minimize token refreshes.\n- Refresh the token when it expires.\n\nThe `AuthTokenFactory` class generates authorization tokens at location update\ntime. The SDK must package the tokens with the update\ninformation to send to Fleet Engine. Make sure that your server-side\nimplementation can issue tokens before initializing the SDK.\n\nFor details of the tokens expected by the Fleet Engine service, see [Issue JSON\nWeb Tokens](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt) for Fleet Engine.\n\nExample of an authorization token fetcher\n\nHere is a skeleton implementation of an `AuthTokenFactory`: \n\n class JsonAuthTokenFactory implements AuthTokenFactory {\n private String vehicleServiceToken; // initially null\n private long expiryTimeMs = 0;\n private String vehicleId;\n\n // This method is called on a thread whose only responsibility is to send\n // location updates. Blocking is OK, but just know that no location updates\n // can occur until this method returns.\n @Override\n public String getToken(AuthTokenContext authTokenContext) {\n String vehicleId = requireNonNull(context.getVehicleId());\n\n if (System.currentTimeMillis() \u003e expiryTimeMs || !vehicleId.equals(this.vehicleId)) {\n // The token has expired, go get a new one.\n fetchNewToken(vehicleId);\n }\n\n return vehicleServiceToken;\n }\n\n private void fetchNewToken(String vehicleId) {\n String url = \"https://yourauthserver.example/token/\" + vehicleId;\n\n try (Reader r = new InputStreamReader(new URL(url).openStream())) {\n com.google.gson.JsonObject obj\n = com.google.gson.JsonParser.parseReader(r).getAsJsonObject();\n vehicleServiceToken = obj.get(\"VehicleServiceToken\").getAsString();\n expiryTimeMs = obj.get(\"TokenExpiryMs\").getAsLong();\n\n // The expiry time could be an hour from now, but just to try and avoid\n // passing expired tokens, we subtract 10 minutes from that time.\n expiryTimeMs -= 10 * 60 * 1000;\n this.vehicleId = vehicleId;\n } catch (IOException e) {\n // It's OK to throw exceptions here. The StatusListener you passed to\n // create the DriverContext class will be notified and passed along the failed\n // update warning.\n throw new RuntimeException(\"Could not get auth token\", e);\n }\n }\n }\n\nThis particular implementation uses the built-in Java HTTP client to fetch a\ntoken in JSON format from the authorization server. The client saves the token\nfor reuse and re-fetches the token if the old token is within 10 minutes of its\nexpiry time.\n\nYour implementation may do things differently, such as using a background thread\nto refresh tokens.\n\nFor the available client libraries for Fleet Engine, see\n[Client libraries for on-demand trips services](/maps/documentation/mobility/fleet-engine/essentials/client-libraries-trips).\n\nWhat's next\n\n[Initialize the Driver SDK](/maps/documentation/mobility/driver-sdk/on-demand/android/initialize-sdk)"]]