Recupera token di autorizzazione

L'SDK Consumer fornisce l'autorizzazione tramite token web JSON. Un token JWT (JSON Web Token) è un token di autorizzazione che fornisce una o più rivendicazioni su un servizio.

L'SDK consumer utilizza il token web JSON fornito dall'applicazione per comunicare con Fleet Engine. Per i dettagli sui token previsti dal server Fleet Engine, consulta Token web JSON e Emettere token web JSON.

Il token di autorizzazione fornisce l'accesso ai seguenti servizi Fleet Engine:

  • TripService: consente all'SDK consumer di accedere ai dettagli del viaggio, tra cui posizione del veicolo, percorso e orario di arrivo stimato. I token di autorizzazione per il servizio di viaggio devono includere un'attestazione tripid:TRIP_ID nell'intestazione authorization del token, dove TRIP_ID è l'ID viaggio del viaggio on demand condiviso.

  • VehicleService: fornisce all'SDK per i consumatori informazioni sulla posizione approssimativa del veicolo per visualizzare il livello di densità dei veicoli e stimare gli orari di arrivo stimati del punto di ritiro. Poiché l'SDK Consumer utilizza solo posizioni approssimative, i token di autorizzazione per il servizio veicolo non richiedono un'attestazione vehicleid.

Che cos'è un token?

Fleet Engine richiede l'utilizzo di token web JSON (JWT) per le chiamate ai metodi API da ambienti a bassa attendibilità: smartphone e browser.

Un JWT ha origine sul tuo server, viene firmato, criptato e trasmesso al client per le successive interazioni con il server fino alla scadenza o alla perdita di validità.

Dettagli chiave

Per saperne di più sui token web JSON, consulta la sezione Token web JSON in Fleet Engine Essentials.

Come ottengono i token i clienti?

Una volta che un autista o un consumatore accede alla tua app utilizzando le credenziali di autorizzazione appropriate, tutti gli aggiornamenti emessi da quel dispositivo devono utilizzare i token di autorizzazione appropriati, che comunicano a Fleet Engine le autorizzazioni per l'app.

In qualità di sviluppatore, l'implementazione del client deve fornire la possibilità di eseguire le seguenti operazioni:

  • Recupera un token web JSON dal tuo server.
  • Riutilizza il token fino alla scadenza per ridurre al minimo gli aggiornamenti del token.
  • Aggiorna il token quando scade.

La classe AuthTokenFactory genera token di autorizzazione al momento dell'aggiornamento della posizione. L'SDK deve includere i token con le informazioni di aggiornamento da inviare a Fleet Engine. Prima di inizializzare l'SDK, assicurati che l'implementazione lato server possa emettere token.

Per i dettagli sui token previsti dal servizio Fleet Engine, vedi Emettere token web JSON per Fleet Engine.

Esempio di un recuperatore di token di autorizzazione

Il seguente esempio di codice mostra come implementare un callback del token di autorizzazione.

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

Passaggi successivi

Inizializza l'SDK Consumer