获取授权令牌

什么是令牌?

对于从低信任环境进行的 API 方法调用,车队引擎要求使用由适当服务账号签名的 JSON Web 令牌 (JWT)。低信任的环境包括智能手机和浏览器。JWT 源自您的服务器,后者是一个完全受信任的环境。JWT 经过签名和加密,并传递给客户端,以供后续服务器使用 直至过期或失效。如需查看服务账号角色列表,请参阅车队引擎基础知识中的车队引擎服务账号角色。

相反,您的后端应针对 Fleet Engine 进行身份验证和授权 使用标准应用默认凭据 机制。

如需详细了解 JSON Web 令牌,请参阅车队引擎必备知识中的 JSON Web 令牌

客户端如何获取令牌?

驾驶员或消费者使用相应的 授权凭据,那么从该设备发布的任何更新都必须使用 相应的授权令牌,用于向 Fleet Engine 传达 应用权限。

作为开发者,您的客户端实现应该能够 以下:

  • 从您的服务器提取 JSON 网络令牌。
  • 在令牌过期之前重复使用,以最大限度地减少令牌刷新。
  • 在令牌过期时刷新。

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

如需详细了解 Fleet Engine 服务预期的令牌,请参阅问题 JSON 适用于 Fleet Engine 的 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