Cloud Run ではコール時に認証をかける設定をすることでセキュアなアクセスを実現できます。
Google Cloud のリファレンスだと Google の http クライアントを使ったトークンの受け渡しになっているためそのままでは Spring Framework の提供している RestTemplate クラスを使ったリクエストができません。
ここでは RestTemplate クラスを使ったトークン渡しでの Run アプリへのアクセス方法を書き残します。
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.RequestEntity.BodyBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.IdTokenCredentials;
import com.google.auth.oauth2.IdTokenProvider;
final String CLOUD_RUN_AUDIENCE = "https://xxx.region.run.app";
final String CLOUD_RUN_URL = "https://xxx.region.run.app/rest/hoge";
// トークンを発行する
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(CLOUD_RUN_AUDIENCE)
.build();
tokenCredential.refresh();
AccessToken token = tokenCredential.getAccessToken();
String accessToken = token.getTokenValue();
// RestTemplate のインスタンスにトークンを付与して Run のアプリをコールする
RestTemplate template = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.USER_AGENT, "agent");
httpHeaders.add(HttpHeaders.CONTENT_TYPE, "text/plain");
httpHeaders.setBearerAuth(accessToken);
BodyBuilder bb = RequestEntity.method( HttpMethod.GET, CLOUD_RUN_URL);
for (Entry<String, List<String>> header : httpHeaders.entrySet()) {
bb.header(header.getKey(), header.getValue().toArray(new String[0]));
}
ResponseEntity<byte[]> response = template.exchange(bb.body(new byte[0]), byte[].class);
System.out.println("response : " + response.getBody());