Compute 메타데이터 서버에 대한 액세스 권한으로 Google Cloud에 호스팅된 서비스는 서비스와 연결된 서비스 계정 ID를 사용하여 OAuth 인증 토큰을 생성할 수 있습니다. Cloud Run 서비스의 허용된 호출자로서 이 토큰을 사용하여 서비스를 인증할 수 있습니다.
더 살펴보기
이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.
코드 샘플
Go
import (
"context"
"fmt"
"io"
"google.golang.org/api/idtoken"
)
// `makeGetRequest` makes a request to the provided `targetURL`
// with an authenticated client using audience `audience`.
func makeGetRequest(w io.Writer, targetURL string, audience string) error {
// Example `audience` value (Cloud Run): https://my-cloud-run-service.run.app/
// (`targetURL` and `audience` will differ for non-root URLs and GET parameters)
ctx := context.Background()
// client is a http.Client that automatically adds an "Authorization" header
// to any requests made.
client, err := idtoken.NewClient(ctx, audience)
if err != nil {
return fmt.Errorf("idtoken.NewClient: %v", err)
}
resp, err := client.Get(targetURL)
if err != nil {
return fmt.Errorf("client.Get: %v", err)
}
defer resp.Body.Close()
if _, err := io.Copy(w, resp.Body); err != nil {
return fmt.Errorf("io.Copy: %v", err)
}
return nil
}
Java
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.IdTokenCredentials;
import com.google.auth.oauth2.IdTokenProvider;
import java.io.IOException;
public class Authentication {
// makeGetRequest makes a GET request to the specified Cloud Run or
// Cloud Functions endpoint `serviceUrl` (must be a complete URL), by
// authenticating with an ID token retrieved from Application Default
// Credentials using the specified `audience`.
//
// Example `audience` value (Cloud Run): https://my-cloud-run-service.run.app/
public static HttpResponse makeGetRequest(String serviceUrl, String audience) throws IOException {
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
if (!(credentials instanceof IdTokenProvider)) {
throw new IllegalArgumentException("Credentials are not an instance of IdTokenProvider.");
}
IdTokenCredentials tokenCredential =
IdTokenCredentials.newBuilder()
.setIdTokenProvider((IdTokenProvider) credentials)
.setTargetAudience(audience)
.build();
GenericUrl genericUrl = new GenericUrl(serviceUrl);
HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(tokenCredential);
HttpTransport transport = new NetHttpTransport();
HttpRequest request = transport.createRequestFactory(adapter).buildGetRequest(genericUrl);
return request.execute();
}
}
Node.js
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// Example: https://my-cloud-run-service.run.app/books/delete/12345
// const url = 'https://TARGET_HOSTNAME/TARGET_URL';
// Example (Cloud Run): https://my-cloud-run-service.run.app/
// const targetAudience = 'https://TARGET_AUDIENCE/';
const {GoogleAuth} = require('google-auth-library');
const auth = new GoogleAuth();
async function request() {
console.info(`request ${url} with target audience ${targetAudience}`);
const client = await auth.getIdTokenClient(targetAudience);
const res = await client.request({url});
console.info(res.data);
}
request().catch(err => {
console.error(err.message);
process.exitCode = 1;
});
Python
import urllib
import google.auth.transport.requests
import google.oauth2.id_token
def make_authorized_get_request(endpoint, audience):
"""
make_authorized_get_request makes a GET request to the specified HTTP endpoint
by authenticating with the ID token obtained from the google-auth client library
using the specified audience value.
"""
# Cloud Run uses your service's hostname as the `audience` value
# audience = 'https://my-cloud-run-service.run.app/'
# For Cloud Run, `endpoint` is the URL (hostname + path) receiving the request
# endpoint = 'https://my-cloud-run-service.run.app/my/awesome/url'
req = urllib.request.Request(endpoint)
auth_req = google.auth.transport.requests.Request()
id_token = google.oauth2.id_token.fetch_id_token(auth_req, audience)
req.add_header("Authorization", f"Bearer {id_token}")
response = urllib.request.urlopen(req)
return response.read()
다음 단계
다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.