Yetkilendirme jetonları alma

Consumer SDK, JSON Web Jetonları kullanarak yetkilendirme sağlar. JSON Web Token (JWT), bir hizmetle ilgili bir veya daha fazla talep sağlayan bir yetkilendirme jetonudur.

Tüketici SDK'sı, Fleet Engine ile iletişim kurmak için uygulama tarafından sağlanan JSON Web Token'ı kullanır. Fleet Engine sunucusu tarafından beklenen jetonlarla ilgili ayrıntılar için JSON Web Jetonları ve JSON Web Jetonları Oluşturma başlıklı makaleleri inceleyin.

Yetkilendirme jetonu, aşağıdaki Fleet Engine hizmetlerine erişim sağlar:

  • TripService: Tüketici SDK'sına, araç konumu, rota ve tahmini varış zamanı dahil olmak üzere seyahat ayrıntılarına erişim izni verir. Gezi hizmeti için yetkilendirme jetonları, jetonun authorization üstbilgisinde bir tripid:TRIP_ID talebi içermelidir. Burada TRIP_ID, paylaşılan isteğe bağlı geziye ait gezi kimliğidir.

  • VehicleService: Araç yoğunluğu katmanını görüntülemek ve teslim alma noktası tahmini varış zamanlarını tahmin etmek için Tüketici SDK'sına yaklaşık araç konumu hakkında bilgi verir. Consumer SDK yalnızca yaklaşık konumları kullandığı için araç hizmeti yetkilendirme jetonları vehicleid talebi gerektirmez.

Jeton nedir?

Fleet Engine, düşük güvenli ortamlardan (akıllı telefonlar ve tarayıcılar) gelen API yöntemi çağrıları için JSON Web Jetonlarının (JWT'ler) kullanılmasını gerektirir.

JWT, sunucunuzda oluşturulur, imzalanır, şifrelenir ve süresi dolana veya geçerliliğini yitirene kadar sonraki sunucu etkileşimleri için istemciye iletilir.

Önemli ayrıntılar

JSON Web Jetonları hakkında daha fazla bilgi için Fleet Engine Essentials'daki JSON Web Jetonları bölümüne bakın.

Müşteriler jetonları nasıl alır?

Bir sürücü veya tüketici, uygun yetkilendirme kimlik bilgilerini kullanarak uygulamanıza giriş yaptıktan sonra, bu cihazdan verilen tüm güncellemelerde uygun yetkilendirme jetonları kullanılmalıdır. Bu jetonlar, Fleet Engine'e uygulamanın izinlerini bildirir.

Geliştirici olarak, istemci uygulamanızın aşağıdakileri yapabilmesi gerekir:

  • Sunucunuzdan bir JSON Web Token alın.
  • Jeton yenileme işlemlerini en aza indirmek için jetonun süresi dolana kadar yeniden kullanın.
  • Jetonun süresi dolduğunda yenileyin.

AuthTokenFactory sınıfı, konum güncelleme zamanında yetkilendirme jetonları oluşturur. SDK, Fleet Engine'e gönderilecek güncelleme bilgileriyle birlikte jetonları paketlemelidir. SDK'yı başlatmadan önce sunucu tarafı uygulamanızın jeton verebildiğinden emin olun.

Fleet Engine hizmetinin beklediği jetonlarla ilgili ayrıntılar için Fleet Engine için JSON Web Jetonları Verme başlıklı makaleyi inceleyin.

Yetkilendirme jetonu getirme aracı örneği

Aşağıdaki kod örneğinde, yetkilendirme jetonu geri çağırmasının nasıl uygulanacağı gösterilmektedir.

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

Sırada ne var?

Consumer SDK'yı başlatma