获取授权令牌
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
什么是令牌?
对于来自低信任环境(智能手机和浏览器)的 API 方法调用,Fleet Engine 要求使用 JSON Web 令牌 (JWT)。
JWT 源自您的服务器,经过签名和加密后传递给客户端,以供后续服务器交互使用,直到过期或不再有效为止。
关键细节
如需详细了解 JSON Web 令牌,请参阅 Fleet Engine 基础知识中的 JSON Web 令牌。
客户如何获取令牌?
司机或消费者使用相应的授权凭据登录您的应用后,从该设备发出的任何更新都必须使用相应的授权令牌,以便向 Fleet Engine 传达应用的权限。
作为开发者,您的客户端实现应提供以下功能:
- 从服务器获取 JSON Web 令牌。
- 重复使用令牌,直到其过期,以尽可能减少令牌刷新次数。
- 在令牌过期时刷新令牌。
AuthTokenFactory
类会在位置信息更新时生成授权令牌。SDK 必须将令牌与更新信息一起打包,然后发送到 Fleet Engine。在初始化 SDK 之前,请确保您的服务器端实现可以发放令牌。
如需详细了解 Fleet Engine 服务所需的令牌,请参阅为 Fleet Engine签发 JSON Web 令牌。
授权令牌提取器的示例
下面是 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
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-31。
[null,null,["最后更新时间 (UTC):2025-08-31。"],[[["\u003cp\u003eFleet Engine requires JSON Web Tokens (JWTs) for API calls from low-trust environments like smartphones and browsers, which are generated on your server and passed to the client.\u003c/p\u003e\n"],["\u003cp\u003eYour server should authenticate with Fleet Engine using Application Default Credentials and issue JWTs signed by an appropriate service account.\u003c/p\u003e\n"],["\u003cp\u003eClients must fetch, reuse, and refresh these JWTs to authorize their interactions with Fleet Engine, ensuring they have the necessary permissions.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eAuthTokenFactory\u003c/code\u003e class facilitates the process of generating and managing authorization tokens within your client application.\u003c/p\u003e\n"],["\u003cp\u003eRefer to the provided links for detailed information about JWTs, service accounts, and client libraries.\u003c/p\u003e\n"]]],[],null,["# Get authorization tokens\n\nWhat is a token?\n----------------\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--------------------------\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-----------------------------------------\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 scheduled tasks services](/maps/documentation/mobility/fleet-engine/essentials/client-libraries-tasks).\n\nWhat's next\n-----------\n\n[Initialize the Driver SDK](/maps/documentation/mobility/driver-sdk/scheduled/android/initialize-sdk)"]]