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

Authenticate calls to Google Cloud Functions programmatically

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

您必须使用已签名的身份令牌调用您的 Cloud Functions(或 Cloud 运行,两者相同)。

因此您可以使用 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. I also wrote a Medium article for explaining the use cases

的工具

您只能使用身份令牌访问您的安全云功能。

1.Create a service accountroles/cloudfunctions.invoker

2.Create 一个只允许经过身份验证的请求的云函数

  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)