Skip to content

Commit 1462fb2

Browse files
Introducing Firebase Authentication module (spring-attic#2157)
* Firebase authentication principal extraction. * starter * sample app
1 parent 8d8adbe commit 1462fb2

File tree

26 files changed

+1517
-2
lines changed

26 files changed

+1517
-2
lines changed

pom.xml

+1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
<module>spring-cloud-gcp-logging</module>
4343
<module>spring-cloud-gcp-data-firestore</module>
4444
<module>spring-cloud-gcp-bigquery</module>
45+
<module>spring-cloud-gcp-security-firebase</module>
4546
</modules>
4647

4748
<properties>

spring-cloud-gcp-autoconfigure/pom.xml

+7-1
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,13 @@
263263
<artifactId>spring-security-oauth2-resource-server</artifactId>
264264
<optional>true</optional>
265265
</dependency>
266-
266+
267+
<dependency>
268+
<groupId>org.springframework.cloud</groupId>
269+
<artifactId>spring-cloud-gcp-security-firebase</artifactId>
270+
<optional>true</optional>
271+
</dependency>
272+
267273
<!-- Actuator -->
268274
<dependency>
269275
<groupId>org.springframework.boot</groupId>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*
2+
* Copyright 2020-2020 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.cloud.gcp.autoconfigure.security;
18+
19+
20+
import java.util.ArrayList;
21+
import java.util.List;
22+
23+
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
24+
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
25+
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
26+
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
27+
import org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration;
28+
import org.springframework.boot.context.properties.EnableConfigurationProperties;
29+
import org.springframework.cloud.gcp.autoconfigure.core.GcpContextAutoConfiguration;
30+
import org.springframework.cloud.gcp.core.GcpProjectIdProvider;
31+
import org.springframework.cloud.gcp.security.firebase.FirebaseJwtTokenDecoder;
32+
import org.springframework.cloud.gcp.security.firebase.FirebaseTokenValidator;
33+
import org.springframework.context.annotation.Bean;
34+
import org.springframework.context.annotation.Configuration;
35+
import org.springframework.http.client.SimpleClientHttpRequestFactory;
36+
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
37+
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
38+
import org.springframework.security.oauth2.jwt.Jwt;
39+
import org.springframework.security.oauth2.jwt.JwtDecoder;
40+
import org.springframework.security.oauth2.jwt.JwtIssuerValidator;
41+
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
42+
import org.springframework.web.client.RestOperations;
43+
import org.springframework.web.client.RestTemplate;
44+
45+
/**
46+
*
47+
* @author Vinicius Carvalho
48+
* @since 1.3
49+
*/
50+
@Configuration
51+
@ConditionalOnProperty(value = "spring.cloud.gcp.security.firebase.enabled", matchIfMissing = true)
52+
@AutoConfigureBefore(OAuth2ResourceServerAutoConfiguration.class)
53+
@AutoConfigureAfter(GcpContextAutoConfiguration.class)
54+
@EnableConfigurationProperties(FirebaseAuthenticationProperties.class)
55+
public class FirebaseAuthenticationAutoConfiguration {
56+
57+
private static final String ISSUER_TEMPLATE = "https://securetoken.google.com/%s";
58+
59+
@Bean
60+
@ConditionalOnMissingBean(name = "firebaseJwtDelegatingValidator")
61+
public DelegatingOAuth2TokenValidator<Jwt> firebaseJwtDelegatingValidator(JwtIssuerValidator jwtIssuerValidator, GcpProjectIdProvider gcpProjectIdProvider) {
62+
List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
63+
validators.add(new JwtTimestampValidator());
64+
validators.add(jwtIssuerValidator);
65+
validators.add(new FirebaseTokenValidator(gcpProjectIdProvider.getProjectId()));
66+
return new DelegatingOAuth2TokenValidator<>(validators);
67+
}
68+
69+
@Bean
70+
@ConditionalOnMissingBean
71+
public JwtDecoder firebaseAuthenticationJwtDecoder(
72+
DelegatingOAuth2TokenValidator<Jwt> firebaseJwtDelegatingValidator,
73+
FirebaseAuthenticationProperties properties) {
74+
return new FirebaseJwtTokenDecoder(restOperations(), properties.getPublicKeysEndpoint(),
75+
firebaseJwtDelegatingValidator);
76+
}
77+
78+
@Bean
79+
public JwtIssuerValidator jwtIssuerValidator(GcpProjectIdProvider gcpProjectIdProvider) {
80+
return new JwtIssuerValidator(String.format(ISSUER_TEMPLATE, gcpProjectIdProvider.getProjectId()));
81+
}
82+
83+
private RestOperations restOperations() {
84+
SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
85+
clientHttpRequestFactory.setConnectTimeout(5_000);
86+
clientHttpRequestFactory.setReadTimeout(2_000);
87+
return new RestTemplate(clientHttpRequestFactory);
88+
}
89+
90+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
* Copyright 2020-2020 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.cloud.gcp.autoconfigure.security;
18+
19+
import org.springframework.boot.context.properties.ConfigurationProperties;
20+
21+
/**
22+
* Firebase Authentication application properties.
23+
*
24+
* @author Vinicius Carvalho
25+
* @since 1.3
26+
*/
27+
@ConfigurationProperties("spring.cloud.gcp.security.firebase")
28+
public class FirebaseAuthenticationProperties {
29+
30+
/**
31+
* Link to Google's public endpoint containing Firebase public keys.
32+
*/
33+
private String publicKeysEndpoint = "https://www.googleapis.com/robot/v1/metadata/x509/[email protected]";
34+
35+
36+
public String getPublicKeysEndpoint() {
37+
return publicKeysEndpoint;
38+
}
39+
40+
public void setPublicKeysEndpoint(String publicKeysEndpoint) {
41+
this.publicKeysEndpoint = publicKeysEndpoint;
42+
}
43+
}

spring-cloud-gcp-autoconfigure/src/main/resources/META-INF/spring.factories

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ org.springframework.cloud.gcp.autoconfigure.trace.StackdriverTraceAutoConfigurat
1414
org.springframework.cloud.gcp.autoconfigure.datastore.DatastoreRepositoriesAutoConfiguration,\
1515
org.springframework.cloud.gcp.autoconfigure.spanner.SpannerRepositoriesAutoConfiguration,\
1616
org.springframework.cloud.gcp.autoconfigure.security.IapAuthenticationAutoConfiguration,\
17+
org.springframework.cloud.gcp.autoconfigure.security.FirebaseAuthenticationAutoConfiguration,\
1718
org.springframework.cloud.gcp.autoconfigure.vision.CloudVisionAutoConfiguration,\
1819
org.springframework.cloud.gcp.autoconfigure.datastore.GcpDatastoreEmulatorAutoConfiguration,\
1920
org.springframework.cloud.gcp.autoconfigure.bigquery.GcpBigQueryAutoConfiguration,\
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/*
2+
* Copyright 2017-2020 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.cloud.gcp.autoconfigure.security;
18+
19+
import com.google.api.gax.core.CredentialsProvider;
20+
import com.google.auth.Credentials;
21+
import org.junit.Test;
22+
23+
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
24+
import org.springframework.boot.autoconfigure.AutoConfigurations;
25+
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
26+
import org.springframework.cloud.gcp.core.GcpProjectIdProvider;
27+
import org.springframework.cloud.gcp.security.firebase.FirebaseJwtTokenDecoder;
28+
import org.springframework.context.annotation.Bean;
29+
30+
import static org.assertj.core.api.Assertions.assertThat;
31+
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
32+
import static org.mockito.Mockito.mock;
33+
34+
35+
/**
36+
* @author Vinicius Carvalho
37+
* @since 1.3
38+
*/
39+
public class FirebaseAuthenticationAutoConfigurationTests {
40+
41+
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
42+
.withConfiguration(
43+
AutoConfigurations.of(FirebaseAuthenticationAutoConfiguration.class, TestConfig.class));
44+
45+
@Test
46+
public void testAutoConfigurationLoaded() throws Exception {
47+
this.contextRunner
48+
.withPropertyValues("spring.cloud.gcp.security.firebase.enabled=true")
49+
.run(context -> {
50+
FirebaseJwtTokenDecoder decoder = context.getBean(FirebaseJwtTokenDecoder.class);
51+
assertThat(decoder).isNotNull();
52+
});
53+
}
54+
55+
@Test
56+
public void testAutoConfigurationNotLoaded() throws Exception {
57+
this.contextRunner
58+
.withPropertyValues("spring.cloud.gcp.security.firebase.enabled=false")
59+
.run(context -> {
60+
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
61+
.isThrownBy(() -> context.getBean(FirebaseJwtTokenDecoder.class));
62+
});
63+
}
64+
65+
66+
67+
static class TestConfig {
68+
69+
@Bean
70+
public GcpProjectIdProvider projectIdProvider() {
71+
return () -> "spring-firebase-test-project";
72+
}
73+
74+
@Bean
75+
public CredentialsProvider googleCredentials() {
76+
return () -> mock(Credentials.class);
77+
}
78+
79+
}
80+
81+
}

spring-cloud-gcp-dependencies/pom.xml

+10
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,11 @@
9494
<artifactId>spring-cloud-gcp-bigquery</artifactId>
9595
<version>${project.version}</version>
9696
</dependency>
97+
<dependency>
98+
<groupId>org.springframework.cloud</groupId>
99+
<artifactId>spring-cloud-gcp-security-firebase</artifactId>
100+
<version>${project.version}</version>
101+
</dependency>
97102

98103
<!--Starters-->
99104
<dependency>
@@ -166,6 +171,11 @@
166171
<artifactId>spring-cloud-gcp-starter-security-iap</artifactId>
167172
<version>${project.version}</version>
168173
</dependency>
174+
<dependency>
175+
<groupId>org.springframework.cloud</groupId>
176+
<artifactId>spring-cloud-gcp-starter-security-firebase</artifactId>
177+
<version>${project.version}</version>
178+
</dependency>
169179
<dependency>
170180
<groupId>org.springframework.cloud</groupId>
171181
<artifactId>spring-cloud-gcp-starter-vision</artifactId>

spring-cloud-gcp-samples/pom.xml

+1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
<module>spring-cloud-gcp-data-firestore-sample</module>
5151
<module>spring-cloud-gcp-bigquery-sample</module>
5252
<module>spring-cloud-gcp-pubsub-stream-binder-functional-sample</module>
53+
<module>spring-cloud-gcp-security-firebase-sample</module>
5354
</modules>
5455

5556
<!-- Checkstyle on samples invoked during CI or manually when running locally. -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
= Spring Cloud GCP Firebase Authentication Sample application
2+
3+
This sample application demonstrates how to use link:../../spring-cloud-gcp-starters/spring-cloud-gcp-starter-security-firebase[Spring Cloud GCP Firebase Authentication Starter] to extract user identity from a signed https://firebase.google.com/[Firebase] JWT token.
4+
5+
The application provides a secured controller that can only be reached if a valid JWT token is sent as an HTTP Header.
6+
7+
This sample app provides simple login page using https://github.com/firebase/firebaseui-web[firebase-ui] to fetch the JWT token.
8+
9+
== Pre requisites
10+
11+
1. Create a new firebase project as instructed https://firebase.google.com/docs/web/setup[here]
12+
2. Once you finish the process make sure you configure the following environment variables before running the app:
13+
a. FIREBASE_CONFIG_API_KEY: Should be your "apiKey" value
14+
b. FIREBASE_CONFIG_APP_ID: Should be your "appId" value
15+
3. Make sure that you are authenticated with `gcloud` and you have set the correct `projectId` to be the same project as your Firebase project.
16+
This app uses default login and will rely on that to extract the `projectId` using the `GcpProjectIdProvider`
17+
4. Go to your Firebase project, select the web application you have created and enable two providers: `Google` and `email`
18+
5. (Optional) : You can add a few users to try this out if you rather not use the Google Provider authentication
19+
20+
== Running
21+
22+
`Make sure you executed steps 2 & 3 from prerequisites section`
23+
24+
----
25+
$ ./mvnw clean spring-boot:run
26+
----
27+
28+
Open your browser at http://localhost:8080
29+
30+
There's a single page app with an `ask` button, if you try to click it you should get an error message.
31+
32+
Also try to access the secure endpoint via curl:
33+
34+
----
35+
curl http://localhost:8080/answer
36+
----
37+
38+
You should get a 403 error.
39+
40+
Now login using the button at the top right corner. You can choose between using a valid Google credential, or a user you have added via the Firebase authentication users menu.
41+
42+
Once you are logged in, you should see a panel with the `curl` command.
43+
44+
Try clicking the button again.
45+
46+
You can also copy the `curl` command and execute it now on your console and you should be able to access the endpoint.
47+
48+
49+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
6+
<parent>
7+
<!-- Your own application should inherit from spring-boot-starter-parent -->
8+
<artifactId>spring-cloud-gcp-samples</artifactId>
9+
<groupId>org.springframework.cloud</groupId>
10+
<version>1.3.0.BUILD-SNAPSHOT</version>
11+
</parent>
12+
13+
<properties>
14+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
16+
<java.version>1.8</java.version>
17+
</properties>
18+
19+
<modelVersion>4.0.0</modelVersion>
20+
<name>Spring Cloud GCP Security Firebase Sample</name>
21+
<description>Spring Cloud Firebase Security Sample</description>
22+
<artifactId>spring-cloud-gcp-security-firebase-sample</artifactId>
23+
24+
<dependencyManagement>
25+
<dependencies>
26+
<dependency>
27+
<groupId>org.springframework.cloud</groupId>
28+
<artifactId>spring-cloud-gcp-dependencies</artifactId>
29+
<version>${project.version}</version>
30+
<type>pom</type>
31+
<scope>import</scope>
32+
</dependency>
33+
</dependencies>
34+
</dependencyManagement>
35+
36+
<dependencies>
37+
<dependency>
38+
<groupId>org.springframework.boot</groupId>
39+
<artifactId>spring-boot-starter-web</artifactId>
40+
</dependency>
41+
<dependency>
42+
<groupId>org.springframework.boot</groupId>
43+
<artifactId>spring-boot-starter-freemarker</artifactId>
44+
</dependency>
45+
<dependency>
46+
<groupId>org.springframework.cloud</groupId>
47+
<artifactId>spring-cloud-gcp-starter-security-firebase</artifactId>
48+
</dependency>
49+
</dependencies>
50+
51+
</project>

0 commit comments

Comments
 (0)