認証トークンを取得する

Consumer SDK は、JSON Web Token を使用した認可を提供します。JSON ウェブトークン(JWT)は、サービスに対する 1 つ以上のクレームを提供する認可トークンです。

Consumer SDK は、アプリケーションから提供された JSON ウェブトークンを使用して Fleet Engine と通信します。Fleet Engine サーバーで想定されるトークンの詳細については、JSON ウェブトークンJSON ウェブトークンを発行するをご覧ください。

認証トークンは、次の Fleet Engine サービスへのアクセスを提供します。

  • TripService - Consumer SDK に、車両の位置、ルート、到着予定時刻などのルートの詳細へのアクセス権を付与します。乗車サービス用の認証トークンには、トークンの authorization ヘッダーに tripid:TRIP_ID クレームを含める必要があります。ここで、TRIP_ID は共有されるオンデマンド乗車サービスの乗車 ID です。

  • VehicleService - 車両の密度レイヤの表示と乗車地点の到着予定時刻の推定のために、Consumer SDK に車両のおおよその位置に関する情報を提供します。Consumer SDK はおおよその位置情報のみを使用するため、車両サービスの認証トークンに vehicleid クレームは必要ありません。

トークンとは

Fleet Engine では、スマートフォンやブラウザなどの信頼度の低い環境からの API メソッド呼び出しに JSON Web Token(JWT)を使用する必要があります。

JWT はサーバーで生成され、署名と暗号化が行われてクライアントに渡されます。有効期限が切れるか無効になるまで、以降のサーバーとのやり取りで使用されます。

主な詳細

JSON ウェブトークンの詳細については、Fleet Engine の基本JSON ウェブトークンをご覧ください。

クライアントがトークンを取得する方法

ドライバーまたは消費者が適切な認証情報を使用してアプリにログインすると、そのデバイスから発行される更新はすべて、適切な認証トークンを使用する必要があります。これにより、アプリの権限が Fleet Engine に伝達されます。

デベロッパーとして、クライアント実装で次の操作を行えるようにする必要があります。

  • サーバーから JSON ウェブトークンを取得します。
  • トークンが期限切れになるまで再利用して、トークンの更新を最小限に抑えます。
  • トークンの有効期限が切れたら更新します。

AuthTokenFactory クラスは、位置情報の更新時に承認トークンを生成します。SDK は、トークンを更新情報とともにパッケージ化して Fleet Engine に送信する必要があります。SDK を初期化する前に、サーバーサイドの実装でトークンを発行できることを確認してください。

Fleet Engine サービスで想定されるトークンの詳細については、Fleet Engine の JSON Web Token を発行するをご覧ください。

認証トークン フェッチャーの例

次のコード例は、認証トークン コールバックを実装する方法を示しています。

Java

class JsonAuthTokenFactory implements AuthTokenFactory {

  private static final String TOKEN_URL =
      "https://yourauthserver.example/token";

  private static class CachedToken {
    String tokenValue;
    long expiryTimeMs;
    String tripId;
  }

  private CachedToken token;

  /*

*   This method is called on a background thread. Blocking is OK. However, be
*   aware that no information can be obtained from Fleet Engine until this
*   method returns.
*/
@Override
public String getToken(AuthTokenContext context) {
  // If there is no existing token or token has expired, go get a new one.
  String tripId = context.getTripId();
  if (tripId == null) {
    throw new RuntimeException("Trip ID is missing from AuthTokenContext");
  }
  if (token == null || System.currentTimeMillis() > token.expiryTimeMs ||
      !tripId.equals(token.tripId)) {
    token = fetchNewToken(tripId);
  }
  return token.tokenValue;
}

  private static CachedToken fetchNewToken(String tripId) {
    String url = TOKEN_URL + "/" + tripId;
    CachedToken token = new CachedToken();

    try (Reader r = new InputStreamReader(new URL(url).openStream())) {
      com.google.gson.JsonObject obj
          = com.google.gson.JsonParser.parseReader(r).getAsJsonObject();

      token.tokenValue = obj.get("ServiceToken").getAsString();
      token.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 5 minutes from that time.
    */
    token.expiryTimeMs -= 5 * 60 * 1000;
  } catch (IOException e) {
    /*
    *   It's OK to throw exceptions here. The error listeners will receive the
    *   error thrown here.
    */
    throw new RuntimeException("Could not get auth token", e);
  }
  token.tripId = tripId;

    return token;
  }
}

Kotlin

class JsonAuthTokenFactory : AuthTokenFactory() {

  private var token: CachedToken? = null

  /*

*   This method is called on a background thread. Blocking is OK. However, be
*   aware that no information can be obtained from Fleet Engine until this
*   method returns.
*/
override fun getToken(context: AuthTokenContext): String {
  // If there is no existing token or token has expired, go get a new one.
  val tripId =
    context.getTripId() ?:
      throw RuntimeException("Trip ID is missing from AuthTokenContext")

    if (token == null || System.currentTimeMillis() > token.expiryTimeMs ||
        tripId != token.tripId) {
      token = fetchNewToken(tripId)
    }

    return token.tokenValue
  }

  class CachedToken(
    var tokenValue: String? = "",
    var expiryTimeMs: Long = 0,
    var tripId: String? = "",
  )

  private companion object {
    const val TOKEN_URL = "https://yourauthserver.example/token"

    fun fetchNewToken(tripId: String) {
      val url = "$TOKEN_URL/$tripId"
      val token = CachedToken()

      try {
        val reader = InputStreamReader(URL(url).openStream())

        reader.use {
          val obj = com.google.gson.JsonParser.parseReader(r).getAsJsonObject()

          token.tokenValue = obj.get("ServiceToken").getAsString()
          token.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 5 minutes from that time.
        */
        token.expiryTimeMs -= 5 * 60 * 1000
      }
    } catch (e: IOException) {
      /*
            *   It's OK to throw exceptions here. The error listeners will receive the
            *   error thrown here.
      */
      throw RuntimeException("Could not get auth token", e)
    }

      token.tripId = tripId

      return token
    }
  }
}

次のステップ

Consumer SDK を初期化する