获取授权令牌

什么是令牌?

对于从低信任环境进行的 API 方法调用,车队引擎要求使用由适当服务账号签名的 JSON Web 令牌 (JWT)。低信任的环境包括智能手机和浏览器。JWT 来自您的服务器,这是一个完全可信的环境。JWT 经过签名和加密,并传递给客户端,以供后续服务器使用 直至过期或失效。

您的后端应使用标准应用默认凭据机制对 Fleet Engine 进行身份验证和授权。请务必使用由适当服务账号签名的 JWT。如需查看服务账号角色列表,请参阅车队引擎基础知识中的车队引擎服务账号角色。

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

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

客户如何获取令牌?

当驾驶员或使用方使用适当的授权凭据登录您的应用后,从该设备发出的任何更新都必须使用适当的授权令牌,这些令牌会将应用的权限传达给车队引擎。

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

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

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