الحصول على الرموز المميّزة للتفويض
تنظيم صفحاتك في مجموعات
يمكنك حفظ المحتوى وتصنيفه حسب إعداداتك المفضّلة.
توفّر حزمة تطوير البرامج (SDK) الخاصة بالمستهلك إذن الوصول باستخدام رموز JSON المميّزة للويب. رمز JSON المميّز للويب (JWT) هو رمز مميّز للتفويض يقدّم مطالبة واحدة أو أكثر بشأن خدمة معيّنة.
تستخدم حزمة تطوير البرامج (SDK) الخاصة بالمستهلكين رمز JSON المميّز للويب الذي يوفّره التطبيق للتواصل مع Fleet Engine. للحصول على تفاصيل حول الرموز المميزة التي يتوقعها خادم Fleet Engine، راجِع رموز JSON المميزة للويب وإصدار رموز JSON المميزة للويب.
يوفّر رمز التفويض إمكانية الوصول إلى خدمات Fleet Engine التالية:
TripService
: تمنح حزمة Consumer SDK إذن الوصول إلى تفاصيل الرحلة، بما في ذلك
موقع المركبة ومسارها ووقت الوصول المقدَّر. يجب أن تتضمّن رموز التفويض الخاصة بخدمة الرحلات
مطالبة tripid:TRIP_ID
في عنوان authorization
للرمز المميّز،
حيث TRIP_ID
هو رقم تعريف الرحلة عند الطلب التي تتم مشاركتها.
VehicleService
: تقدّم هذه السمة إلى حزمة تطوير البرامج (SDK) المخصّصة للمستهلكين معلومات حول الموقع الجغرافي التقريبي للمركبة من أجل عرض طبقة كثافة المركبات وتقدير الوقت المقدَّر للوصول إلى نقطة الاستلام. بما أنّ حزمة تطوير البرامج (SDK) الخاصة بالمستهلك تستخدم المواقع الجغرافية التقريبية فقط، لا تتطلّب رموز المصادقة المميزة الخاصة بخدمة المركبة مطالبة vehicleid
.
ما هي الرموز المميزة؟
تتطلّب Fleet Engine استخدام رموز JSON المميّزة للويب (JWT) لإجراء عمليات استدعاء طرق واجهة برمجة التطبيقات
من البيئات ذات مستوى الثقة المنخفض، مثل الهواتف الذكية والمتصفحات.
يتم إنشاء رمز JWT على الخادم الخاص بك، ويتم توقيعه وتشفيره وتمريره إلى العميل
للتفاعلات اللاحقة مع الخادم إلى أن تنتهي صلاحيته أو يصبح غير صالح.
التفاصيل الأساسية
لمزيد من المعلومات حول رموز JSON المميّزة للويب، راجِع رموز JSON المميّزة للويب في أساسيات Fleet Engine.
كيف يحصل العملاء على الرموز المميزة؟
بعد أن يسجّل السائق أو المستهلك الدخول إلى تطبيقك باستخدام بيانات اعتماد التفويض المناسبة، يجب أن تستخدم أي تحديثات صادرة من هذا الجهاز رموز تفويض مناسبة، ما يوضّح لخدمة Fleet Engine أذونات التطبيق.
بصفتك المطوّر، يجب أن يوفّر تنفيذ العميل إمكانية إجراء ما يلي:
- استرجِع رمز JSON المميّز للويب من الخادم.
- أعِد استخدام الرمز المميز إلى أن تنتهي صلاحيته لتقليل عمليات إعادة تحميل الرموز المميزة.
- أعِد تحميل الرمز المميز عند انتهاء صلاحيته.
تنشئ الفئة AuthTokenFactory
رموزًا مميزة للتفويض عند تعديل الموقع الجغرافي. يجب أن تحزم حزمة SDK الرموز المميّزة مع معلومات التعديل لإرسالها إلى Fleet Engine. تأكَّد من أنّ عملية التنفيذ من جهة الخادم يمكنها إصدار الرموز المميزة قبل إعداد حزمة تطوير البرامج (SDK).
للحصول على تفاصيل حول الرموز المميزة التي تتوقّعها خدمة Fleet Engine، يمكنك الاطّلاع على إصدار رموز مميزة JSON للويب في Fleet Engine.
مثال على أداة جلب رمز مميز للتفويض
يوضّح مثال الرمز البرمجي التالي كيفية تنفيذ معاودة الاتصال الخاصة برمز التفويض.
Java
class JsonAuthTokenFactory implements AuthTokenFactory {
private static final String TOKEN_URL =
"https://yourauthserver.example/token";
private static class CachedToken {
String tokenValue;
long expiryTimeMs;
String tripId;
}
private CachedToken token;
/*
* This method is called on a background thread. Blocking is OK. However, be
* aware that no information can be obtained from Fleet Engine until this
* method returns.
*/
@Override
public String getToken(AuthTokenContext context) {
// If there is no existing token or token has expired, go get a new one.
String tripId = context.getTripId();
if (tripId == null) {
throw new RuntimeException("Trip ID is missing from AuthTokenContext");
}
if (token == null || System.currentTimeMillis() > token.expiryTimeMs ||
!tripId.equals(token.tripId)) {
token = fetchNewToken(tripId);
}
return token.tokenValue;
}
private static CachedToken fetchNewToken(String tripId) {
String url = TOKEN_URL + "/" + tripId;
CachedToken token = new CachedToken();
try (Reader r = new InputStreamReader(new URL(url).openStream())) {
com.google.gson.JsonObject obj
= com.google.gson.JsonParser.parseReader(r).getAsJsonObject();
token.tokenValue = obj.get("ServiceToken").getAsString();
token.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 5 minutes from that time.
*/
token.expiryTimeMs -= 5 * 60 * 1000;
} catch (IOException e) {
/*
* It's OK to throw exceptions here. The error listeners will receive the
* error thrown here.
*/
throw new RuntimeException("Could not get auth token", e);
}
token.tripId = tripId;
return token;
}
}
Kotlin
class JsonAuthTokenFactory : AuthTokenFactory() {
private var token: CachedToken? = null
/*
* This method is called on a background thread. Blocking is OK. However, be
* aware that no information can be obtained from Fleet Engine until this
* method returns.
*/
override fun getToken(context: AuthTokenContext): String {
// If there is no existing token or token has expired, go get a new one.
val tripId =
context.getTripId() ?:
throw RuntimeException("Trip ID is missing from AuthTokenContext")
if (token == null || System.currentTimeMillis() > token.expiryTimeMs ||
tripId != token.tripId) {
token = fetchNewToken(tripId)
}
return token.tokenValue
}
class CachedToken(
var tokenValue: String? = "",
var expiryTimeMs: Long = 0,
var tripId: String? = "",
)
private companion object {
const val TOKEN_URL = "https://yourauthserver.example/token"
fun fetchNewToken(tripId: String) {
val url = "$TOKEN_URL/$tripId"
val token = CachedToken()
try {
val reader = InputStreamReader(URL(url).openStream())
reader.use {
val obj = com.google.gson.JsonParser.parseReader(r).getAsJsonObject()
token.tokenValue = obj.get("ServiceToken").getAsString()
token.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 5 minutes from that time.
*/
token.expiryTimeMs -= 5 * 60 * 1000
}
} catch (e: IOException) {
/*
* It's OK to throw exceptions here. The error listeners will receive the
* error thrown here.
*/
throw RuntimeException("Could not get auth token", e)
}
token.tripId = tripId
return token
}
}
}
الخطوات التالية
إعداد حزمة Consumer SDK
إنّ محتوى هذه الصفحة مرخّص بموجب ترخيص Creative Commons Attribution 4.0 ما لم يُنصّ على خلاف ذلك، ونماذج الرموز مرخّصة بموجب ترخيص Apache 2.0. للاطّلاع على التفاصيل، يُرجى مراجعة سياسات موقع Google Developers. إنّ Java هي علامة تجارية مسجَّلة لشركة Oracle و/أو شركائها التابعين.
تاريخ التعديل الأخير: 2025-08-31 (حسب التوقيت العالمي المتفَّق عليه)
[null,null,["تاريخ التعديل الأخير: 2025-08-31 (حسب التوقيت العالمي المتفَّق عليه)"],[[["\u003cp\u003eThe Consumer SDK utilizes JSON Web Tokens (JWTs) for authorization to access trip and vehicle data within Fleet Engine.\u003c/p\u003e\n"],["\u003cp\u003eJWTs are generated by your backend server and passed to the client, granting access to specific Fleet Engine services like TripService and VehicleService.\u003c/p\u003e\n"],["\u003cp\u003eClient applications need to implement logic to fetch, reuse, and refresh these tokens to maintain ongoing access to Fleet Engine.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eAuthTokenFactory\u003c/code\u003e is used to generate authorization tokens which must be included in requests sent to Fleet Engine.\u003c/p\u003e\n"],["\u003cp\u003eImplement a secure token fetching mechanism on your server to provide these tokens for the Consumer SDK.\u003c/p\u003e\n"]]],["The Consumer SDK utilizes JSON Web Tokens (JWTs) for authorization with Fleet Engine. These JWTs, provided by your application, grant access to services like `TripService` (requiring a `tripid` claim) and `VehicleService`. Your client must fetch, reuse, and refresh JWTs from your server. The `AuthTokenFactory` class generates and packages these tokens with update information for Fleet Engine. Server-side implementation must issue tokens before SDK initialization, ensuring devices have proper authorization credentials for updates.\n"],null,["The Consumer SDK provides authorization using JSON Web Tokens. A JSON Web Token\n(JWT) is an authorization token that provides one or more claims on a service.\n\nThe Consumer SDK uses the JSON Web Token provided by the application to\ncommunicate with the Fleet Engine. For details of the tokens expected by the\nFleet Engine server, see [JSON Web Tokens](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/jwt)\nand [Issue JSON Web tokens](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt).\n\nThe authorization token provides access to the following Fleet Engine services:\n\n- **`TripService`** - Gives the Consumer SDK access to trip details, including\n vehicle position, route, and ETA. Authorization tokens for the trip service\n must include a `tripid:TRIP_ID` claim in the token's `authorization` header,\n where `TRIP_ID` is the trip ID of the on-demand trip being shared.\n\n- **`VehicleService`** - Gives the Consumer SDK information about the\n approximate vehicle location for displaying the vehicle density layer and\n estimating pickup point ETAs. Because the Consumer SDK uses only approximate\n locations, authorization tokens for the vehicle service don't require a\n `vehicleid` claim.\n\nWhat 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\nThe following code example demonstrates how to implement an authorization token\ncallback. \n\nJava \n\n class JsonAuthTokenFactory implements AuthTokenFactory {\n\n private static final String TOKEN_URL =\n \"https://yourauthserver.example/token\";\n\n private static class CachedToken {\n String tokenValue;\n long expiryTimeMs;\n String tripId;\n }\n\n private CachedToken token;\n\n /*\n\n * This method is called on a background thread. Blocking is OK. However, be\n * aware that no information can be obtained from Fleet Engine until this\n * method returns.\n */\n @Override\n public String getToken(AuthTokenContext context) {\n // If there is no existing token or token has expired, go get a new one.\n String tripId = context.getTripId();\n if (tripId == null) {\n throw new RuntimeException(\"Trip ID is missing from AuthTokenContext\");\n }\n if (token == null || System.currentTimeMillis() \u003e token.expiryTimeMs ||\n !tripId.equals(token.tripId)) {\n token = fetchNewToken(tripId);\n }\n return token.tokenValue;\n }\n\n private static CachedToken fetchNewToken(String tripId) {\n String url = TOKEN_URL + \"/\" + tripId;\n CachedToken token = new CachedToken();\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\n token.tokenValue = obj.get(\"ServiceToken\").getAsString();\n token.expiryTimeMs = obj.get(\"TokenExpiryMs\").getAsLong();\n\n /*\n\n * The expiry time could be an hour from now, but just to try and avoid\n * passing expired tokens, we subtract 5 minutes from that time.\n */\n token.expiryTimeMs -= 5 * 60 * 1000;\n } catch (IOException e) {\n /*\n * It's OK to throw exceptions here. The error listeners will receive the\n * error thrown here.\n */\n throw new RuntimeException(\"Could not get auth token\", e);\n }\n token.tripId = tripId;\n\n return token;\n }\n }\n\nKotlin \n\n class JsonAuthTokenFactory : AuthTokenFactory() {\n\n private var token: CachedToken? = null\n\n /*\n\n * This method is called on a background thread. Blocking is OK. However, be\n * aware that no information can be obtained from Fleet Engine until this\n * method returns.\n */\n override fun getToken(context: AuthTokenContext): String {\n // If there is no existing token or token has expired, go get a new one.\n val tripId =\n context.getTripId() ?:\n throw RuntimeException(\"Trip ID is missing from AuthTokenContext\")\n\n if (token == null || System.currentTimeMillis() \u003e token.expiryTimeMs ||\n tripId != token.tripId) {\n token = fetchNewToken(tripId)\n }\n\n return token.tokenValue\n }\n\n class CachedToken(\n var tokenValue: String? = \"\",\n var expiryTimeMs: Long = 0,\n var tripId: String? = \"\",\n )\n\n private companion object {\n const val TOKEN_URL = \"https://yourauthserver.example/token\"\n\n fun fetchNewToken(tripId: String) {\n val url = \"$TOKEN_URL/$tripId\"\n val token = CachedToken()\n\n try {\n val reader = InputStreamReader(URL(url).openStream())\n\n reader.use {\n val obj = com.google.gson.JsonParser.parseReader(r).getAsJsonObject()\n\n token.tokenValue = obj.get(\"ServiceToken\").getAsString()\n token.expiryTimeMs = obj.get(\"TokenExpiryMs\").getAsLong()\n\n /*\n\n * The expiry time could be an hour from now, but just to try and avoid\n * passing expired tokens, we subtract 5 minutes from that time.\n */\n token.expiryTimeMs -= 5 * 60 * 1000\n }\n } catch (e: IOException) {\n /*\n * It's OK to throw exceptions here. The error listeners will receive the\n * error thrown here.\n */\n throw RuntimeException(\"Could not get auth token\", e)\n }\n\n token.tripId = tripId\n\n return token\n }\n }\n }\n\nWhat's next\n\n[Initialize the Consumer SDK](/maps/documentation/mobility/journey-sharing/on-demand/android/init-sdk)"]]