Recupera token di autorizzazione

L'SDK consumer fornisce l'autorizzazione utilizzando token web JSON. un token web JSON (JWT) è un token di autorizzazione che fornisce una o più attestazioni su un servizio.

L'SDK consumer utilizza il token web JSON fornito dall'applicazione per comunicare con Fleet Engine. Per i dettagli dei token previsti dal Server Fleet Engine, consulta Token web JSON ed emissione di token web JSON.

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

  • TripService: consente all'SDK consumer di accedere ai dettagli della corsa, tra cui la posizione del veicolo, il percorso e l'orario di arrivo stimato. Token di autorizzazione per il servizio di corsa deve includere una rivendicazione tripid:TRIP_ID nell'intestazione authorization del token, dove TRIP_ID è l'ID della corsa on demand condivisa.

  • VehicleService: fornisce all'SDK consumer informazioni sul posizione approssimativa del veicolo per visualizzare il livello di densità dei veicoli e stima l'orario di arrivo stimato del punto di ritiro. Poiché l'SDK consumer utilizza solo valori approssimati, luoghi, i token di autorizzazione per il servizio veicoli non richiedono vehicleid rivendicazione.

Che cos'è un token?

Fleet Engine richiede l'utilizzo di token web JSON (JWT) firmati da un account di servizio appropriato per le chiamate ai metodi API da bassa attendibilità ambienti cloud-native. Gli ambienti a basso livello di attendibilità includono smartphone e browser. Un JWT viene generato sul tuo server, che è un ambiente completamente attendibile. JWT viene firmato, criptato e passato al client per il successivo server interazioni fino a quando non scade o non è più valido.

Il backend deve autenticarsi e autorizzare Fleet Engine utilizzando meccanismi standard delle Credenziali predefinite dell'applicazione. Marca accertati di utilizzare JWT firmati da un account di servizio appropriato. Per un elenco dei ruoli dell'account di servizio. Vedi i ruoli dell'account di servizio di Fleet Engine in Nozioni di base su Fleet Engine.

Per ulteriori informazioni sui token web JSON, consulta Token web JSON in Fleet Engine Essentials.

In che modo i client ricevono i token?

Quando un conducente o un consumatore accede alla tua app utilizzando l'app credenziali di autorizzazione, eventuali aggiornamenti emessi da tale dispositivo devono utilizzare dei token di autorizzazione appropriati, che comunicano a Fleet Engine autorizzazioni per l'app.

In qualità di sviluppatore, l'implementazione del cliente deve fornire la possibilità di farlo le seguenti:

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

La classe AuthTokenFactory genera token di autorizzazione all'aggiornamento della sede nel tempo. L'SDK deve pacchettizzare i token con l'aggiornamento le informazioni da inviare a Fleet Engine. Assicurati che i server può emettere token prima di inizializzare l'SDK.

Per maggiori dettagli sui token previsti dal servizio Fleet Engine, vedi Problema JSON Web Token per Fleet Engine.

Esempio di un fetcher di token di autorizzazione

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

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

Inizializzare l'SDK consumer