Skip to content

feat(cloudrun): add 'cloudrun_service_to_service_receive' sample #10100

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions run/service-auth/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2025 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.run</groupId>
<artifactId>service-auth</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<!-- The parent pom defines common style checks and testing strategies for our samples.
Removing or replacing it should not affect the execution of the samples in anyway. -->

<parent>
<groupId>com.google.cloud.samples</groupId>
<artifactId>shared-configuration</artifactId>
<version>1.2.0</version>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The parent POM version for shared-configuration is 1.2.0. The PR checklist has an item "pom.xml parent set to latest shared-configuration" which is currently unchecked. Could you confirm if 1.2.0 is indeed the latest version, or if it needs an update?

Copy link

@shawnmjones shawnmjones Aug 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

</parent>
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
<spring-boot.version>3.2.2</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client</artifactId>
<version>1.47.0</version>
</dependency>
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>1.35.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>jib-maven-plugin</artifactId>
<version>3.4.0</version>
<configuration>
<to>
<image>gcr.io/PROJECT_ID/service-auth</image>
</to>
</configuration>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.serviceauth;

// [START cloudrun_service_to_service_receive]

import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.apache.v2.ApacheHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import java.util.Arrays;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class Authentication {
@RestController
class AuthenticationController {

@Autowired private AuthenticationService authService;

@GetMapping("/")
public ResponseEntity<String> getEmailFromAuthHeader(
@RequestHeader(value = "X-Authorization", required = false) String authHeader) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Per the Cloud Run authentication documentation the HTTP header is "Authorization" not "X-Authorization".

String responseBody;
if (authHeader == null) {
responseBody = "Error verifying ID token: missing X-Authorization header";
return new ResponseEntity<>(responseBody, HttpStatus.UNAUTHORIZED);
}

String email = authService.parseAuthHeader(authHeader);
if (email == null) {
responseBody = "Unauthorized request. Please supply a valid bearer token.";
return new ResponseEntity<>(responseBody, HttpStatus.UNAUTHORIZED);
}

responseBody = "Hello, " + email;
return new ResponseEntity<>(responseBody, HttpStatus.OK);
}
}

@Service
public class AuthenticationService {
/*
* Parse the authorization header, validate and decode the Bearer token.
*
* Args:
* authHeader: String of HTTP header with a Bearer token.
*
* Returns:
* A string containing the email from the token.
* null if the token is invalid or the email can't be retrieved.
*/
public String parseAuthHeader(String authHeader) {
// Split the auth type and value from the header.
String[] authHeaderStrings = authHeader.split(" ");
if (authHeaderStrings.length != 2) {
System.out.println("Malformed Authorization header");
return null;
}
String authType = authHeaderStrings[0];
String tokenValue = authHeaderStrings[1];

// Get the service URL from the environment variable
// set at the time of deployment.
String serviceUrl = System.getenv("SERVICE_URL");
// Define the expected audience as the Service Base URL.
Collection<String> audience = Arrays.asList(serviceUrl);

// Validate and decode the ID token in the header.
if ("bearer".equals(authType.toLowerCase())) {
try {
// Find more information about the verification process in:
// https://developers.google.com/identity/sign-in/web/backend-auth#java
// https://cloud.google.com/java/docs/reference/google-api-client/latest/com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier
GoogleIdTokenVerifier verifier =
new GoogleIdTokenVerifier.Builder(new ApacheHttpTransport(), new GsonFactory())
.setAudience(audience)
.build();
GoogleIdToken googleIdToken = verifier.verify(tokenValue);

if (googleIdToken != null) {
// More info about the structure for the decoded ID Token here:
// https://cloud.google.com/docs/authentication/token-types#id
// https://cloud.google.com/java/docs/reference/google-api-client/latest/com.google.api.client.googleapis.auth.oauth2.GoogleIdToken
// https://cloud.google.com/java/docs/reference/google-api-client/latest/com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload
GoogleIdToken.Payload payload = googleIdToken.getPayload();
if (payload.getEmailVerified()) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggest adding this for parity with Python sample:

System.out.println("Email verified: " + payload.getEmail());

return payload.getEmail();
}
System.out.println("Invalid token. Email wasn't verified.");
}
} catch (Exception exception) {
System.out.println("Ivalid token: " + exception);
return null;
}
} else {
System.out.println("Unhandled header format: " + authType);
}
return null;
}
}

public static void main(String[] args) {
SpringApplication.run(Authentication.class, args);
}

// [END cloudrun_service_to_service_receive]
}
Loading