Authenticating user via Firebase Authorizer using Spring Boot

Akhilesh Anthwal
VectoScalar
Published in
5 min readJan 3, 2024

In this article, we’ll learn how to secure our spring boot API using firebase authorization.

Introduction to Firebase Authentication

It is essential to authenticate users, and it is much harder if we have to write all this code on our own. This is done very easily with the help of Firebase. Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, and popular federated identity providers like Google, Microsoft, Facebook, Twitter, and more.

supports popular federated identity provider

How Authentication Works..?

We first get authentication credentials from the user to sign a user into our app.

  • Credentials can be the user’s email address and password.
  • The credential can be an OAuth token from an identity provider.

We then pass these credentials to the Firebase Authentication SDK. Backend services will then verify those credentials and return a response to the client.

authentication

And after a successful sign in-

  • Firebase provides us an authentication token, which is then checked in whatever place we need to authenticate or authorize a user, be it front-end or back-end.
  • We can access the user’s basic profile information.

Prerequisites

  • Make sure that you have a server app.
  • Admin Java SDK — Java 8+

Let’s get started:

Configure Firebase

First, enable the SignIn Methods. I enable Email/Password and Google and create a user. You can simply add a user using email/password.

Configuring Firebase in Spring Boot Project

To configure the firebase in the spring boot project first download the servicesAccountKey.json file from your Firebase Project setting.

Go to Project Setting -> Service Account-> Scroll down and click on create and then click on Generate new Private Key.

This will generate and download Private Key to access the Firebase Admin SDK.

*make sure to keep this file secure

Download the servicesAccountKey.json file and paste it into the resource folder of your spring boot project. This is the location where we access our private key.

servicesAccountKey.json

Add the SDK

If you are setting up a new project, you need to install the SDK for the language of your choice. If you use Maven to build your application, you can add the following dependency to your pom.xml:

<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>9.0.0</version>
</dependency>

for reference, you can visit https://firebase.google.com/docs/admin/setup#windows

Retrieve ID tokens on clients

When a user or device successfully signs in, Firebase creates a corresponding ID token that uniquely identifies them and grants them access to several resources, such as Firebase Realtime Database and Cloud Storage. You can re-use that ID token to identify the user or device on your custom backend server. To retrieve the ID token from the client, make sure the user is signed in and then get the ID token from the signed-in user:

firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
// Send token to your backend via HTTPS
// …
}).catch(function(error) {
// Handle error
});

Once you have an ID token, you can send that JWT to your backend and validate it using the Firebase Admin SDK, or using a third-party JWT library if your server is written in a language that Firebase does not natively support.

Initialize Firebase SDK

//firebase service account

@Configuration
public class FirebaseInitialization {

@Bean
public void initialization() {
try{

FileInputStream serviceAccount =
new FileInputStream("./serviceAccountKey.json");

// serviceAccountKey.json file containing the key, store this json file to your resource folder

FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();

FirebaseApp.initializeApp(options);
} catch (Exception error) {
error.printStackTrace();
}
}
}

Verify ID tokens using the Firebase Admin SDK

The Firebase Admin SDK has a built-in method for verifying and decoding ID tokens. If the provided ID token has the correct format, is not expired, and is properly signed, the method returns the decoded ID token. You can grab the uid of the user or device from the decoded token.

Follow the Admin SDK setup instructions to initialize the Admin SDK with a service account. Then, use the verifyIdToken() method to verify an ID token:

/ idToken comes from the client app
FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(idToken);
String uid = decodedToken.getUid();

HTTP filter to check firebase token

public class FireBaseTokenFilter extends OncePerRequestFilter { 
/**
* Authenticating user via fireBase authorizer verify fireBase token and extract
* Uid and Email from token
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

//Extracts token from header
String token = request.getHeader("Authorization");

//checks if token is there
if (token == null )
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED,"Missing token!");

FirebaseToken decodedToken = null;
try {
//verifies token to firebase server
decodedToken = FirebaseAuth.getInstance().verifyIdToken(token);
} catch (FirebaseAuthException e) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED,"Error! "+e.toString());
}
//if token is invalid
if (decodedToken==null){
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED,"Invalid token!");
}

//Extract Uid and Email
String uid= decodedToken.getUid();
String email = decodedToken.getEmail();

/*
//set Uid and Email to request
void setAttribute(java.lang.String name, java.lang.Object o)
*/

request.setAttribute(“uid”, uid);
request.setAttribute(“email”,email);

chain.doFilter(request,response);
}
}

This is how we can authenticate any user in our spring boot application using firebase.

Thanks for reading!

--

--