什麼是權杖?
Fleet Engine 必須使用 適用於來自 low-trust 的 API 方法呼叫的適當服務帳戶 環境。低信任的環境包括智慧型手機和瀏覽器。JWT 起源於您的伺服器,這也是值得信賴的環境JWT 簽署、加密並傳遞至用戶端,以供後續伺服器使用 互動,直到過期或不再有效。
您的後端應使用 標準的應用程式預設憑證機制。廠牌 請務必使用適當服務帳戶簽署的 JWT。換 服務帳戶角色清單,請參閱 Fleet Engine 服務帳戶角色 詳情請參閱 Fleet Engine 基本概念一文。
如要進一步瞭解 JSON Web Token,請參閱 JSON Web Token ( Fleet Engine Essentials。
用戶端如何取得權杖?
駕駛或消費者使用適當的 授權憑證,凡是從該裝置發出的更新都必須使用 取得適當的授權權杖,向 Fleet Engine 和 授予所需的應用程式權限
身為開發人員,客戶導入作業必須能進行以下操作: 包括:
- 從伺服器擷取 JSON Web Token。
- 重複使用權杖直到過期為止,以盡量減少權杖重新整理次數。
- 請在權杖過期時重新整理。
AuthTokenFactory
類別會在位置更新時產生授權權杖
讓應用程式從可以最快做出回應的位置
回應使用者要求SDK 必須將權杖與更新檔封裝
資訊以傳送至 Fleet Engine確認伺服器端
實作時可能會在 SDK 初始化前發出符記。
如要進一步瞭解 Fleet Engine 服務預期的權杖,請參閱核發 JSON Fleet Engine 適用的網路權杖。
授權權杖擷取工具範例
以下是 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 用戶端程式庫,請參閱 適用於排程工作服務的用戶端程式庫。