取得授權權杖
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
什麼是權杖?
從低信任度環境 (智慧型手機和瀏覽器) 呼叫 API 方法時,Fleet Engine 必須使用 JSON Web Token (JWT)。
JWT 會在伺服器上產生、簽署、加密,並傳遞至用戶端,供後續伺服器互動使用,直到 JWT 過期或失效為止。
重要詳細資料
如要進一步瞭解 JSON Web Token,請參閱Fleet Engine 基礎知識中的「JSON Web Token」。
用戶如何取得權杖?
駕駛人或消費者使用適當的授權憑證登入應用程式後,從該裝置發出的任何更新都必須使用適當的授權權杖,向 Fleet Engine 傳達應用程式的權限。
身為開發人員,您的用戶端實作項目應提供下列功能:
- 從伺服器擷取 JSON Web Token。
- 在權杖過期前重複使用,盡量減少權杖更新次數。
- 權杖到期時,請重新整理。
AuthTokenFactory
類別會在位置資訊更新時產生授權權杖。SDK 必須將權杖與更新資訊封裝在一起,然後傳送至 Fleet Engine。請先確認伺服器端實作項目可以發出權杖,再初始化 SDK。
如要瞭解 Fleet Engine 服務預期的權杖詳細資料,請參閱「為 Fleet Engine 簽發 JSON Web Token」。
授權權杖擷取器範例
以下是 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);
}
}
}
這項實作方式會使用內建的 Java HTTP 用戶端,從授權伺服器擷取 JSON 格式的權杖。用戶端會儲存權杖以供重複使用,如果舊權杖即將在 10 分鐘內到期,則會重新擷取權杖。
您的實作方式可能不同,例如使用背景執行緒重新整理權杖。
如要瞭解 Fleet Engine 適用的用戶端程式庫,請參閱隨選行程服務適用的用戶端程式庫。
後續步驟
初始化 Driver SDK
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-31 (世界標準時間)。
[null,null,["上次更新時間:2025-08-31 (世界標準時間)。"],[[["\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)"]]