Android user authentication using Firebase with Spring boot backend — Part 2

Richy Great
2 min readApr 25, 2021
Photo by Sarvenaz Sorour on Unsplash

In the previous tutorial, we have seen how to prepare the android app for Google sign in using Firebase. In this tutorial, we will see how to quickly integrate firebase security into your spring boot application. When the API calls originating from the mobile application sends the Bearer token in the Authorization header, spring should be able to use this for authentication and authorization.

Bearer Token in Android

Before each HTTP call to the backend, use the FirebaseAuth object to get the OAuth bearer token. This can be done as follows.

FirebaseUser firebaseUser = mAuth.getCurrentUser();
if (firebaseUser == null) {
Toast.makeText(context, "Google Login failed", Toast.LENGTH_SHORT).show();
return;
}
firebaseUser.getIdToken(true)

After the getIdToken method’s completion, you can get the bearer token from the GetTokenResult. This should be passed in the Authorization header with the prefix “Bearer” in all the calls to the backend.

Spring Boot Firebase integration

The only pending item in our checklist is to capture this Authorization token in the Rest API request and use it for auth. Follow the below steps to do so.

  1. Copy the google-services.json file to the resources directory of the Spring Boot app.
  2. Add spring cloud and spring cloud gcp dependencies. Check for the latest version and group id as the below configuration is for Hoxton.SR8 cloud version.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring.cloud-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gcp-dependencies</artifactId>
<version>${spring-cloud-gcp.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

3. Add spring-cloud-gcp-starter-security-firebase to the dependencies

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gcp-starter-security-firebase</artifactId>
</dependency>

4. Setup spring.cloud.gcp properties in application.yml

spring.cloud.gcp:
project-id: softwok
credentials.location: classpath:/google-services.json

That is all we need to secure our Spring Boot Rest API using Firebase, we can now inject Authentication in our rest controller to even fetch the Firebase userId. This can be used for distributed tracing across mobile and backend.

If you are interested in setting up Spring Boot for AWS, read the below article.

--

--