승인 토큰 가져오기

소비자 SDK는 JSON 웹 토큰을 사용하여 승인을 제공합니다. JSON 웹 토큰 (JWT)는 서비스에 하나 이상의 클레임을 제공하는 승인 토큰입니다.

소비자 SDK는 애플리케이션이 제공하는 JSON 웹 토큰을 사용하여 통신할 수 있습니다 Fleet Engine 서버(JSON 웹 토큰 참고) 및 JSON 웹 토큰 발행을 참조하세요.

승인 토큰은 다음 Fleet Engine 서비스에 대한 액세스를 제공합니다.

  • TripService: 소비자 SDK에 다음과 같은 경로 세부정보에 대한 액세스 권한을 부여합니다. 차량 위치, 경로, 도착예정시간 등이 있습니다. 이동 서비스의 승인 토큰 토큰의 authorization 헤더에 tripid:TRIP_ID 클레임을 포함해야 합니다. 여기서 TRIP_ID는 공유할 주문형 경로의 이동 ID입니다.

  • VehicleService - 소비자 SDK에 차량 밀도 레이어를 표시하기 위한 대략적인 차량 위치 및 승차 지점 도착예정시간을 예상하고 있습니다. 소비자 SDK는 차량 서비스의 승인 토큰은 vehicleid 소유권 주장.

토큰이란 무엇인가요?

Fleet Engine을 사용하려면 서명된 JSON 웹 토큰 (JWT)을 사용해야 합니다. 신뢰도가 낮은 API 메서드 호출을 위한 적절한 서비스 계정 환경을 참조하세요. 신뢰도가 낮은 환경에는 스마트폰과 브라우저가 포함됩니다. JWT 완전히 신뢰할 수 있는 환경인 서버에서 시작됩니다. JWT 서명되고 암호화되어 후속 서버를 위해 클라이언트에 전달됩니다. 만료되거나 더 이상 유효하지 않을 때까지 상호작용하지 않습니다.

백엔드는 다음을 사용하여 Fleet Engine에 대해 인증 및 승인해야 합니다. 표준 애플리케이션 기본 사용자 인증 정보 메커니즘을 사용합니다. 제조업체 적절한 서비스 계정으로 서명된 JWT를 사용해야 합니다. 서비스 계정 역할 목록은 Fleet Engine 서비스 계정 역할 참조 Fleet Engine 기본사항 참고

JSON 웹 토큰에 대한 자세한 내용은 JSON 웹 토큰을 참조하세요. Fleet Engine Essentials.

클라이언트가 토큰을 가져오는 방법

운전자나 소비자가 적절한 앱을 사용해 앱에 로그인하면 인증 사용자 인증 정보를 갖추고 있으므로 해당 기기에서 발급되는 모든 업데이트는 적절한 승인 토큰이 있어야 합니다. 권한을 부여할 수 있습니다.

개발자의 클라이언트 구현은 다음과 같은 기능을 제공해야 합니다. 다음과 같습니다.

  • 서버에서 JSON 웹 토큰을 가져옵니다.
  • 만료될 때까지 토큰을 재사용하여 토큰 새로고침을 최소화하세요.
  • 토큰이 만료되면 새로고침합니다.

AuthTokenFactory 클래스는 위치 업데이트 시 승인 토큰을 생성합니다. 있습니다. SDK는 업데이트로 토큰을 패키징해야 합니다. Fleet Engine으로 전송할 정보가 포함됩니다 서버 측 서버의 SDK를 초기화하기 전에 토큰을 발급할 수 있습니다.

Fleet Engine 서비스에서 예상하는 토큰에 대한 자세한 내용은 JSON 발행을 참조하세요. 웹 토큰을 참조하세요.

승인 토큰 가져오기 프로그램의 예

다음 코드 예에서는 승인 토큰을 구현하는 방법을 보여줍니다. 있습니다.

자바

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
    }
  }
}

다음 단계

소비자 SDK 초기화