קבלת אסימוני הרשאה

‫Consumer SDK מספק הרשאה באמצעות אסימוני אינטרנט מסוג JSON. אסימון אינטרנט מסוג JSON ‏(JWT) הוא אסימון הרשאה שמספק טענה אחת או יותר לגבי שירות.

כדי לתקשר עם Fleet Engine, ה-Consumer SDK משתמש ב-JSON Web Token שסופק על ידי האפליקציה. פרטים על הטוקנים שנדרשים לשרת Fleet Engine מופיעים במאמרים טוקנים של JSON Web והנפקת טוקנים של JSON Web.

אסימון ההרשאה מספק גישה לשירותים הבאים של Fleet Engine:

  • ‫TripService – נותן ל-Consumer SDK גישה לפרטי הנסיעה, כולל מיקום הרכב, המסלול וזמן ההגעה המשוער. אסימוני ההרשאה לשירות הנסיעות חייבים לכלול הצהרה מסוג tripid:TRIP_ID בכותרת authorization של האסימון, כאשר TRIP_ID הוא מזהה הנסיעה של הנסיעה לפי דרישה שמשותפת.

  • VehicleService – מספק ל-Consumer SDK מידע על המיקום המשוער של הרכב כדי להציג את שכבת צפיפות הרכבים ולהעריך את זמני ההגעה המשוערים לנקודת האיסוף. מכיוון ש-Consumer SDK משתמש רק במיקומים משוערים, אסימוני ההרשאה לשירות הרכב לא דורשים הצהרה על vehicleid.

מה זה טוקן?

כדי להפעיל שיטות API מסביבות עם רמת אמינות נמוכה (סמארטפונים ודפדפנים), צריך להשתמש ב-Fleet Engine בטוקנים של JSON Web (JWT).

מקור ה-JWT הוא בשרת שלכם, הוא חתום, מוצפן ומועבר ללקוח לאינטראקציות הבאות עם השרת עד שהוא פג תוקף או לא תקף יותר.

פרטים חשובים

מידע נוסף על אסימוני אינטרנט מסוג JSON מופיע בקטע אסימוני אינטרנט מסוג JSON במאמר מידע בסיסי על Fleet Engine.

איך הלקוחות מקבלים אסימונים?

אחרי שנהג או צרכן מתחברים לאפליקציה באמצעות פרטי הכניסה המתאימים, כל העדכונים שמונפקים מהמכשיר הזה חייבים להשתמש בטוקנים מתאימים של הרשאה, שמעבירים ל-Fleet Engine את ההרשאות של האפליקציה.

כמפתחים, הטמעת הלקוח צריכה לספק את היכולת לבצע את הפעולות הבאות:

  • אחזור של אסימון אינטרנט מסוג JSON מהשרת.
  • כדי לצמצם את מספר הרענונים של האסימון, כדאי להשתמש בו שוב עד שיפוג התוקף שלו.
  • מרעננים את הטוקן כשתוקפו פג.

המחלקה AuthTokenFactory יוצרת טוקנים של הרשאה בזמן עדכון לגבי מיקום. ערכת ה-SDK צריכה לארוז את האסימונים עם פרטי העדכון כדי לשלוח אותם אל Fleet Engine. לפני שמפעילים את ה-SDK, צריך לוודא שההטמעה בצד השרת יכולה להנפיק טוקנים.

כדי לדעת אילו טוקנים נדרשים לשירות Fleet Engine, קראו את המאמר הנפקת טוקנים של JSON Web ל-Fleet Engine.

דוגמה לאחזור אסימון הרשאה

בדוגמת הקוד הבאה אפשר לראות איך מטמיעים קריאה חוזרת (callback) של אסימון הרשאה.

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