获取授权令牌

什么是令牌?

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

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

关键细节

如需详细了解 JSON Web 令牌,请参阅 Fleet Engine 基础知识中的 JSON Web 令牌

客户如何获取令牌?

司机或消费者使用相应的授权凭据登录您的应用后,从该设备发出的任何更新都必须使用相应的授权令牌,以便向 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