Skip to content
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.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>
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.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");
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);

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]
}
Loading