取得授權權杖

什麼是權杖?

低信任度環境 (智慧型手機和瀏覽器) 呼叫 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