-
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
Open
alarconesparza
wants to merge
11
commits into
GoogleCloudPlatform:main
Choose a base branch
from
alarconesparza:alarconesparza-feat-add-service-to-service-sample-receive
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
866ff5b
feat(cloudrun): add 'cloudrun_service_to_service_receive' sample
alarconesparza 747db93
fix lint issue
alarconesparza 4893ca6
Merge branch 'GoogleCloudPlatform:main' into alarconesparza-feat-add-…
alarconesparza 44b3db3
fix comments from gemini
alarconesparza ba0f479
add crossorigin
alarconesparza 0f5df2d
fix issues with header
alarconesparza bbc57aa
improve testing times
alarconesparza e984e49
remove crossorigin
alarconesparza 6c7bc3a
solve comments from reviewer
alarconesparza 967bde3
add waitForServer method
alarconesparza 2cc8bc2
Use Authorization header
alarconesparza File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.2</version> | ||
</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> |
131 changes: 131 additions & 0 deletions
131
run/service-auth/src/main/java/com/example/serviceauth/Authentication.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
/* | ||
* Copyright 2025 Google LLC | ||
iennae marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* | ||
* 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.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.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 { | ||
|
||
private final AuthenticationService authService = new AuthenticationService(); | ||
|
||
@GetMapping("/") | ||
public ResponseEntity<String> getEmailFromAuthHeader( | ||
@RequestHeader(value = "Authorization", required = false) String authHeader) { | ||
String responseBody; | ||
if (authHeader == null) { | ||
responseBody = "Error verifying ID token: missing 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."; | ||
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); | ||
} | ||
} | ||
|
||
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"); | ||
glasnt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return null; | ||
} | ||
String authType = authHeaderStrings[0]; | ||
String tokenValue = authHeaderStrings[1]; | ||
// Validate and decode the ID token in the header. | ||
if (!"bearer".equals(authType.toLowerCase())) { | ||
System.out.println("Unhandled header format: " + authType); | ||
return null; | ||
} | ||
|
||
// 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); | ||
shawnmjones marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
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); | ||
|
||
// 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()) { | ||
System.out.println("Invalid token. Email wasn't verified."); | ||
return null; | ||
} | ||
System.out.println("Email verified: " + payload.getEmail()); | ||
return payload.getEmail(); | ||
|
||
} catch (Exception exception) { | ||
System.out.println("Ivalid token: " + exception); | ||
} | ||
return null; | ||
} | ||
} | ||
|
||
public static void main(String[] args) { | ||
SpringApplication.run(Authentication.class, args); | ||
} | ||
|
||
// [END cloudrun_service_to_service_receive] | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.