-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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,135 @@ | ||
/* | ||
* Copyright 2025 Google LLC | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
* | ||
* 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.HttpHeaders; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.stereotype.Service; | ||
import org.springframework.web.bind.annotation.CrossOrigin; | ||
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 | ||
@CrossOrigin(exposedHeaders = "*", allowedHeaders = "*") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Using |
||
class AuthenticationController { | ||
|
||
@Autowired private AuthenticationService authService; | ||
|
||
@GetMapping("/") | ||
public ResponseEntity<String> getEmailFromAuthHeader( | ||
@RequestHeader("X-Serverless-Authorization") String authHeader) { | ||
String responseBody; | ||
if (authHeader == null) { | ||
responseBody = "Error verifying ID token: missing X-Serverless-Authorization header"; | ||
return new ResponseEntity<>(responseBody, HttpStatus.UNAUTHORIZED); | ||
Comment on lines
+51
to
+53
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The |
||
} | ||
|
||
String email = authService.parseAuthHeader(authHeader); | ||
if (email == null) { | ||
responseBody = "Unauthorized request. Please supply a valid bearer token."; | ||
HttpHeaders headers = new HttpHeaders(); | ||
headers.add("WWW-Authenticate", "Bearer"); | ||
return new ResponseEntity<>(responseBody, headers, 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"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Using For example, using SLF4J: import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// ... inside the class
private static final Logger logger = LoggerFactory.getLogger(AuthenticationService.class);
// ... in the method
logger.warn("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); | ||
Comment on lines
+93
to
+95
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If the Should we add a check for |
||
|
||
// Validate and decode the ID token in the header. | ||
if ("Bearer".equals(authType)) { | ||
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()) { | ||
return payload.getEmail(); | ||
} | ||
System.out.println("Invalid token. Email wasn't verified."); | ||
} | ||
} catch (Exception exception) { | ||
System.out.println("Ivalid token: " + exception); | ||
} | ||
Comment on lines
+120
to
+122
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Catching the generic |
||
} 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] | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is the copyright year 2025 intentional? It seems like a placeholder and should likely be the current year (2024) or the year of creation.