0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring Framework の RestTemplate を使って Cloud Run アプリを OAuth 認証トークン付きでコールする方法

Last updated at Posted at 2025-01-10

Cloud Run ではコール時に認証をかける設定をすることでセキュアなアクセスを実現できます。

image.png

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());

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?