groovy 以编程方式验证对Google Cloud Functions的调用

8yoxcaq7  于 2023-06-28  发布在  Go
关注(0)|答案(2)|浏览(161)

我正在尝试从SAP CPI向Google Cloud Functions进行身份验证,以便从数据库中获取一些数据。为了推送数据,我们使用pub/sub,带有服务帐户访问令牌,它工作得很好。但是对于函数,它需要身份令牌而不是访问令牌。我们使用groovy脚本(No Jenkins)获取前面的token。
是否也可以使用访问令牌对函数进行身份验证?或者在不构建整个IAP层的情况下获得身份令牌?

6yoyoihd

6yoyoihd1#

您必须使用签名的身份令牌调用您的Cloud Functions(或Cloud Run,这是相同的)。
因此您可以使用groovy脚本来生成一个签名的身份令牌。这里有一个例子

import com.google.api.client.http.GenericUrl
import com.google.api.client.http.HttpRequest
import com.google.api.client.http.HttpRequestFactory
import com.google.api.client.http.HttpResponse
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.auth.Credentials
import com.google.auth.http.HttpCredentialsAdapter
import com.google.auth.oauth2.IdTokenCredentials
import com.google.auth.oauth2.IdTokenProvider
import com.google.auth.oauth2.ServiceAccountCredentials
import com.google.common.base.Charsets
import com.google.common.io.CharStreams

String myUri = "YOUR_URL";

Credentials credentials = ServiceAccountCredentials
        .fromStream(new FileInputStream(new File("YOUR_SERVICE_ACCOUNT_KEY_FILE"))).createScoped("https://www.googleapis.com/auth/cloud-platform");

String token = ((IdTokenProvider) credentials).idTokenWithAudience(myUri, Collections.EMPTY_LIST).getTokenValue();
System.out.println(token);

IdTokenCredentials idTokenCredentials = IdTokenCredentials.newBuilder()
        .setIdTokenProvider((ServiceAccountCredentials) credentials)
        .setTargetAudience(myUri).build();

HttpRequestFactory factory = new NetHttpTransport().createRequestFactory(new HttpCredentialsAdapter(idTokenCredentials));
HttpRequest request = factory.buildGetRequest(new GenericUrl(myUri));
HttpResponse httpResponse = request.execute();

System.out.println(CharStreams.toString(new InputStreamReader(httpResponse.getContent(), Charsets.UTF_8)));
  • 仅当您不在GCP时,才需要服务帐户密钥文件。否则,默认服务帐户就足够了,但必须是服务帐户。您的个人用户帐户将无法使用 *

添加此依赖项(在Maven中)

<dependency>
            <groupId>com.google.auth</groupId>
            <artifactId>google-auth-library-oauth2-http</artifactId>
            <version>0.20.0</version>
        </dependency>

或者您可以使用I wrote and open sourced工具。wrote a Medium article for explaining the use cases

nvbavucw

nvbavucw2#

您只能使用身份令牌访问受保护的云功能。

  1. Create a service accountroles/cloudfunctions.invoker
    2.创建一个只允许经过身份验证的请求的云函数
https://REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession

target_audience = 'https://REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME'

creds = service_account.IDTokenCredentials.from_service_account_file(
        '/path/to/svc.json', target_audience=target_audience)

authed_session = AuthorizedSession(creds)

# make authenticated request and print the response, status_code
resp = authed_session.get(target_audience)
print(resp.status_code)
print(resp.text)

相关问题