Skip to content

Commit fca10f8

Browse files
committed
Update Auth sample to use Google Library
1 parent 3db6d74 commit fca10f8

File tree

4 files changed

+46
-79
lines changed

4 files changed

+46
-79
lines changed

run/authentication/README.md

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
# Authenticating service-to-service
22

3-
This sample shows how to make an authenticated request by retrieving a JSON Web Tokens (JWT) from the [metadata server](https://cloud.google.com/run/docs/securing/service-identity#identity_tokens).
3+
This sample shows how to make an authenticated request by retrieving a JSON Web Tokens (JWT) from [Application Default Credentials](https://cloud.google.com/docs/authentication/production#finding_credentials_automatically).
44

55
For more details on how to work with this sample read [Authenticating service-to-service](https://cloud.google.com/run/docs/authenticating/service-to-service).
6-
7-
**Note** You cannot query an instance's metadata from another instance or directly from your local computer. For testing purposes, this sample uses the environment variable, `"GOOGLE_CLOUD_PROJECT"`, to determine local or instance environment. To run tests locally, make sure environment variable, `"GOOGLE_CLOUD_PROJECT"`, is not set.

run/authentication/pom.xml

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<?xml version="1.0" encoding="UTF-8"?>
1+
<?xml version="1.0" encoding="UTF-8" ?>
22
<!--
33
Copyright 2019 Google LLC
44
Licensed under the Apache License, Version 2.0 (the "License");
@@ -35,9 +35,9 @@ limitations under the License.
3535

3636
<dependencies>
3737
<dependency>
38-
<groupId>com.squareup.okhttp3</groupId>
39-
<artifactId>okhttp</artifactId>
40-
<version>4.6.0</version>
38+
<groupId>com.google.auth</groupId>
39+
<artifactId>google-auth-library-oauth2-http</artifactId>
40+
<version>0.20.0</version>
4141
</dependency>
4242

4343
<dependency>
@@ -46,6 +46,11 @@ limitations under the License.
4646
<version>4.13</version>
4747
<scope>test</scope>
4848
</dependency>
49-
49+
<dependency>
50+
<groupId>org.hamcrest</groupId>
51+
<artifactId>hamcrest-library</artifactId>
52+
<version>1.3</version>
53+
<scope>test</scope>
54+
</dependency>
5055
</dependencies>
51-
</project>
56+
</project>

run/authentication/src/main/java/com/example/cloudrun/Authentication.java

Lines changed: 26 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -17,47 +17,38 @@
1717
package com.example.cloudrun;
1818

1919
// [START run_service_to_service_auth]
20+
import com.google.api.client.http.GenericUrl;
21+
import com.google.api.client.http.HttpRequest;
22+
import com.google.api.client.http.HttpResponse;
23+
import com.google.api.client.http.HttpTransport;
24+
import com.google.api.client.http.javanet.NetHttpTransport;
25+
import com.google.auth.http.HttpCredentialsAdapter;
26+
import com.google.auth.oauth2.GoogleCredentials;
27+
import com.google.auth.oauth2.IdTokenCredentials;
28+
import com.google.auth.oauth2.IdTokenProvider;
2029
import java.io.IOException;
21-
import java.util.concurrent.TimeUnit;
22-
import okhttp3.OkHttpClient;
23-
import okhttp3.Request;
24-
import okhttp3.Response;
2530

2631
public class Authentication {
2732

28-
// Instantiate OkHttpClient
29-
private static final OkHttpClient ok =
30-
new OkHttpClient.Builder()
31-
.readTimeout(10, TimeUnit.SECONDS)
32-
.writeTimeout(10, TimeUnit.SECONDS)
33-
.build();
34-
3533
// makeGetRequest makes a GET request to the specified Cloud Run endpoint,
36-
// serviceUrl (must be a complete URL), by authenticating with the Id token
37-
// obtained from the Metadata API.
38-
public static Response makeGetRequest(String serviceUrl) throws IOException {
39-
Request.Builder serviceRequest = new Request.Builder().url(serviceUrl);
40-
41-
// Set up metadata server request
42-
// https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature
43-
String tokenUrl =
44-
String.format(
45-
"http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=%s",
46-
serviceUrl);
47-
Request tokenRequest =
48-
new Request.Builder().url(tokenUrl).addHeader("Metadata-Flavor", "Google").get().build();
49-
// Fetch the token
50-
try (Response tokenResponse = ok.newCall(tokenRequest).execute()) {
51-
String token = tokenResponse.body().string();
52-
// Provide the token in the request to the receiving service
53-
serviceRequest.addHeader("Authorization", "Bearer " + token);
54-
System.out.println("Id token query succeeded.");
55-
} catch (IOException e) {
56-
System.out.println("Id token query failed: " + e);
34+
// serviceUrl (must be a complete URL), by authenticating with an Id token
35+
// retrieved from Application Default Credentials.
36+
public static HttpResponse makeGetRequest(String serviceUrl) throws IOException {
37+
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
38+
if (!(credentials instanceof IdTokenProvider)) {
39+
throw new IllegalArgumentException("Credentials are not an instance of IdTokenProvider.");
5740
}
58-
59-
return ok.newCall(serviceRequest.get().build()).execute();
41+
IdTokenCredentials tokenCredential =
42+
IdTokenCredentials.newBuilder()
43+
.setIdTokenProvider((IdTokenProvider) credentials)
44+
.setTargetAudience(serviceUrl)
45+
.build();
46+
47+
GenericUrl genericUrl = new GenericUrl(serviceUrl);
48+
HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(tokenCredential);
49+
HttpTransport transport = new NetHttpTransport();
50+
HttpRequest request = transport.createRequestFactory(adapter).buildGetRequest(genericUrl);
51+
return request.execute();
6052
}
6153
}
6254
// [END run_service_to_service_auth]
63-

run/authentication/src/test/java/com/example/cloudrun/AuthenticationTest.java

Lines changed: 8 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -17,48 +17,22 @@
1717
package com.example.cloudrun;
1818

1919
import static org.hamcrest.MatcherAssert.assertThat;
20+
import static org.hamcrest.Matchers.equalTo;
2021
import static org.hamcrest.core.StringContains.containsString;
2122

22-
import java.io.ByteArrayOutputStream;
23+
import com.google.api.client.http.HttpResponse;
2324
import java.io.IOException;
24-
import java.io.PrintStream;
25-
import org.junit.After;
26-
import org.junit.Before;
2725
import org.junit.Test;
2826

2927
public class AuthenticationTest {
30-
private ByteArrayOutputStream bout;
31-
private PrintStream out;
32-
String expectedResp;
33-
34-
@Before
35-
public void setUp() {
36-
bout = new ByteArrayOutputStream();
37-
out = new PrintStream(bout);
38-
System.setOut(out);
39-
40-
// This test uses the existence of env var "GOOGLE_CLOUD_PROJECT"
41-
// to determine local vs GCP environment only for testing purposes.
42-
if (System.getenv("GOOGLE_CLOUD_PROJECT") != null) {
43-
expectedResp = "Id token query succeeded";
44-
System.out.println("Running on GCP...");
45-
} else {
46-
expectedResp = "Id token query failed";
47-
System.out.println("Running locally...");
48-
}
49-
}
50-
51-
@After
52-
public void tearDown() {
53-
System.setOut(null);
54-
}
5528

5629
@Test
5730
public void canMakeGetRequest() throws IOException {
58-
String url = "http://example.com/";
59-
Authentication.makeGetRequest(url);
60-
String got = bout.toString();
61-
assertThat(got, containsString(expectedResp));
31+
String url = "https://example.com";
32+
HttpResponse response = Authentication.makeGetRequest(url);
33+
assertThat(response.parseAsString(), containsString("Example Domain"));
34+
assertThat(response.getContentType(), containsString("text/html"));
35+
assertThat(response.getStatusCode(), equalTo(200));
6236
}
6337

6438
@Test
@@ -67,8 +41,7 @@ public void failsMakeGetRequestWithoutProtocol() throws IOException {
6741
try {
6842
Authentication.makeGetRequest(url);
6943
} catch (IllegalArgumentException e) {
70-
assertThat(e.getMessage(), containsString("Expected URL scheme 'http' or 'https'"));
44+
assertThat(e.getMessage(), containsString("no protocol"));
7145
}
7246
}
7347
}
74-

0 commit comments

Comments
 (0)