In this article, we will configure a Spring Boot application to authenticate using the Firebase authentication token.
Disclaimer: This article was originally a response to this medium article
I used some different configurations (e.g. I’m not using Spring oauth-resource-server library)
and more updated code (with Spring-Security 6.3.1) Then I realized that the answer was too long and I needed to write a short tutorial about it.
All the (working) code is available in this git repository.
Libraries
Let’s start with the libraries needed:
As you can see, we don’t really need anything special in here. Just the standard spring-starter-web and security,
with a sprinkle Firebase Admin SDK.
Firebase Config
Configuring Firebase with the following props:
And the following Property class: (this is mapped 1-1 with the properties automatically)
We can correctly initialize the needed @Bean FirebaseAuth that we will need to verify the JWT token:
Spring Security Config
The core of the security Configuration is in the SecurityConfig class:
Here we have disabled the Cors, Csrf, and added the FirebaseAuthenticationFilter in a specific position in the long
Spring Security Filter Chain. The FirebaseAuthenticationFilter will check the token (only for the WebConstants.API_BASE_PATH requests) and provide
the Authentication object to the SecurityContext.
It’s a good practice use a custom Authentication Token, instead of using the old UsernamePasswordAuthenticationToken.
In this case, we have the FirebaseAuthenticationToken:
In the getAuthoritiesFromToken() method we will convert the Custom Claims of the Firebase Authentication Document,
that are transmitted in the JWT token, into a list of GrantedAuthorities.
Adding Claims to a User
In order to add the claims to a user, you can use the Firebase Admin SDK. Here is an example:
As you can see, the method is protected by the ADMIN authority, which means in practice that
if the user does not have in the Authentication table the correct “Claims.authorities”, the request will be rejected
with a 403 error.
Conclusion
In this short tutorial, we have seen some updated configurations to play with Firebase Auth and
Spring Security. I want to thank the original author of the article, Sebastijan Comsysto
who inspired me to write this one.