什麼是權杖?
Fleet Engine 規定,從低信任環境 (智慧型手機和瀏覽器) 呼叫 API 方法時,必須使用 JSON Web Token (JWT)。
JWT 源自伺服器,經過簽署和加密,並傳遞至用戶端,用於後續的伺服器互動,直到過期或失效為止。
重要詳細資料
- 使用應用程式預設憑證,向 Fleet Engine 進行驗證及授權。
- 使用適當的服務帳戶簽署 JWT。請參閱「Fleet Engine 基本概念」中的「Fleet Engine 服務帳戶角色」。
如要進一步瞭解 JSON Web Token,請參閱「Fleet Engine 基本概念」中的「JSON Web Token」。
用戶端如何取得權杖?
司機或消費者使用適當的授權憑證登入應用程式後,從該裝置發出的任何更新都必須使用適當的授權權杖,以便向 Fleet Engine 傳達應用程式的權限。
開發人員應在用戶端實作中提供下列功能:
- 從伺服器擷取 JSON Web Token。
- 重複使用權杖,直到權杖到期,盡可能減少權杖更新次數。
- 在權杖到期時更新。
AuthTokenFactory 類別會在位置更新通知時產生授權權杖。SDK 必須將權杖與更新資訊一併封裝,然後傳送至 Fleet Engine。請確認伺服器端實作項目可核發權杖,再初始化 SDK。
如要進一步瞭解 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 適用的用戶端程式庫,請參閱「隨選行程服務適用的用戶端程式庫」。