GCP 存储 - 未提供签名密钥

GCP Storage - signing key not provided

尽管我在这里发现了类似的问题:

Signing key was not provided and could not be derived on google precondition

这无法解决我的问题。

我在本地对 Google 存储默认服务帐户进行身份验证,我可以轻松读取存储桶对象,如下所示:

    private val storage: Storage = StorageOptions
        .newBuilder()
        .setProjectId(projectId)
        .build()
        .service

    fun read() {
        val blob = storage
            .get(BlobId.of(bucket, object))

        println(String(blob.getContent()))
    }

然而,当我尝试生成签名上传 url 时:

    fun uploadUrl(objectName: String): String = storage
        .signUrl(
            BlobInfo.newBuilder(BlobId.of(bucketName, objectName)).build(),
            15,
            TimeUnit.MINUTES,
            Storage.SignUrlOption.httpMethod(HttpMethod.PUT),
            Storage.SignUrlOption.withExtHeaders(mapOf("Content-Type" to "application/octet-stream")),
            Storage.SignUrlOption.withV4Signature()
        )
        .toString()

我得到 signing key not provided

我发现很难认清我到底错过了什么。我通过 gcloud auth application-default loginowner 用户的身份验证,通常允许我执行任何 gcloud 任务。这里有什么区别?

要签名,您需要一个私钥。使用用户凭据,您不能,因为您的环境中只有一个刷新令牌。但是,在服务帐户密钥文件中,您有一个私钥。您可以下载并使用它,但出于安全原因,我不喜欢它。

wrote an article and I found a workaround in Python。我在 Java 中构建了一个类似的 hack(抱歉,我不是 kotlin dev!但我确定它每个都可以转换!)。

Storage storage = StorageOptions.getDefaultInstance().getService();

Credentials credentialsToSIgn = storage.getOptions().getCredentials();
if (credentialsToSIgn instanceof UserCredentials) {
  credentialsToSIgn = ImpersonatedCredentials.create(
    (GoogleCredentials) credentialsToSIgn,
    "SERVICE_ACCOUNT_EMAIL",
    Collections.EMPTY_LIST, 
    Collections.EMPTY_LIST, 
    3600);
}
System.out.println(
  storage.signUrl(
    BlobInfo.newBuilder(BlobId.of(bucketName, objectName)).build(),
    15,
    TimeUnit.MINUTES,
    Storage.SignUrlOption.httpMethod(HttpMethod.PUT),
    Storage.SignUrlOption.withExtHeaders(mapOf("Content-Type" to "application/octet-stream")),
    Storage.SignUrlOption.withV4Signature()
    Storage.SignUrlOption.signWith((ServiceAccountSigner) credentialsToSIgn)
  )
);

ImpersonatedCredentials 只是在这里使用 sign method in the class. This sign method uses the IAMUtils.sign method which call the Service Account Credential API,如我的文章

这不是一个很好的技巧,但它确实有效。您可以将服务帐户电子邮件放在参数中,并在本地环境之外将其省略,以确保不会在其他地方执行错误操作。