获取授权令牌

什么是令牌?

Fleet Engine 要求使用 JSON Web 令牌 (JWT) 从 低信任环境 (智能手机和浏览器)调用 API 方法。

JWT 源自您的服务器,经过签名、加密,然后传递给客户端 ,以供后续服务器交互使用,直到过期或失效为止。

重要详细信息

如需详细了解 JSON Web 令牌,请参阅 JSON Web 令牌(位于 Fleet Engine 基础知识中)。

客户端如何获取令牌?

当司机或消费者使用适当的 授权凭据登录您的应用后,从该设备发出的任何更新都必须使用 适当的授权令牌,该令牌会向 Fleet Engine 传达应用的 权限。

作为开发者,您的客户端实现应提供 以下功能:

  • 从您的服务器获取 JSON Web 令牌。
  • 重复使用令牌,直到令牌过期,以尽量减少令牌刷新次数。
  • 在令牌过期时刷新令牌。

AuthTokenFactory 类会在位置信息更新时生成授权令牌。SDK 必须将令牌与更新 信息打包在一起,然后发送给 Fleet Engine。请确保您的服务器端 实现可以在初始化 SDK 之前颁发令牌。

如需详细了解 Fleet Engine 服务所需的令牌,请参阅为 Fleet Engine 颁发 JSON Web 令牌

授权令牌获取器示例

下面是 AuthTokenFactory 的框架实现:

class JsonAuthTokenFactory implements AuthTokenFactory {
  private String vehicleServiceToken;  // initially null
  private long expiryTimeMs = 0;
  private String vehicleId;

  // This method is called on a thread whose only responsibility is to send
  // location updates. Blocking is OK, but just know that no location updates
  // can occur until this method returns.
  @Override
  public String getToken(AuthTokenContext authTokenContext) {
    String vehicleId = requireNonNull(context.getVehicleId());

    if (System.currentTimeMillis() > expiryTimeMs || !vehicleId.equals(this.vehicleId)) {
      // The token has expired, go get a new one.
      fetchNewToken(vehicleId);
    }

    return vehicleServiceToken;
  }

  private void fetchNewToken(String vehicleId) {
    String url = "https://yourauthserver.example/token/" + vehicleId;

    try (Reader r = new InputStreamReader(new URL(url).openStream())) {
      com.google.gson.JsonObject obj
          = com.google.gson.JsonParser.parseReader(r).getAsJsonObject();
      vehicleServiceToken = obj.get("VehicleServiceToken").getAsString();
      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 10 minutes from that time.
      expiryTimeMs -= 10 * 60 * 1000;
      this.vehicleId = vehicleId;
    } catch (IOException e) {
      // It's OK to throw exceptions here. The StatusListener you passed to
      // create the DriverContext class will be notified and passed along the failed
      // update warning.
      throw new RuntimeException("Could not get auth token", e);
    }
  }
}

此特定实现使用内置的 Java HTTP 客户端从授权服务器获取 JSON 格式的令牌。客户端会保存令牌 以供重复使用,如果旧令牌距离过期时间不到 10 分钟,则会重新获取令牌 。

您的实现可能会以不同的方式执行操作,例如使用后台线程 刷新令牌。

如需了解适用于 Fleet Engine 的可用客户端库,请参阅 按需行程服务的客户端库

后续步骤

初始化 Driver SDK