public ServiceAccountAccessToken generateAccessToken()

in token-service/src/main/java/com/google/solutions/tokenservice/oauth/ServiceAccount.java [155:199]


  public ServiceAccountAccessToken generateAccessToken(
    List<String> scopes,
    Duration lifetime
  ) throws ApiException, IOException {
    Preconditions.checkNotNull(scopes, "scopes");
    Preconditions.checkNotNull(lifetime, "lifetime");
    Preconditions.checkArgument(!lifetime.isNegative(), "lifetime");

    try {
      var request = new GenerateAccessTokenRequest()
        .setScope(scopes)
        .setLifetime(lifetime.toSeconds() + "s");

      var issueTime = Instant.now();
      var response = createClient()
        .projects()
        .serviceAccounts()
        .generateAccessToken(resourceName(), request)
        .execute();

      return new ServiceAccountAccessToken(
        response.getAccessToken(),
        String.join(" ", scopes),
        issueTime,
        Instant.parse(response.getExpireTime()));
    }
    catch (GoogleJsonResponseException e) {
      switch (e.getStatusCode()) {
        case 400:
          throw new IllegalArgumentException(
            "Generating access token failed",
            ApiException.from(e));
        case 401:
          throw new NotAuthenticatedException(
            "Not authenticated",
            ApiException.from(e));
        case 403:
          throw new AccessDeniedException(
            String.format("Access to service account '%s' was denied", this.id),
            ApiException.from(e));
        default:
          throw ApiException.from((GoogleJsonResponseException)e.fillInStackTrace());
      }
    }
  }