Let’s touch base.. with Firebase 🔥
Tags: webdev, productivity, tutorial, java
Published: 2020-08-29 11:18:04

To put it mildly, Firebase is a <b>beast</b>. 

There are so many facets of Firebase which make it a dream platform for many start ups, side projects and quick hack ups. That’s not to say you can’t scale up massively with Firebase, just ask Google Play Music which has a cool 5 Billion installs. 

Just to name a few features without scratching the technical depth that Firebase has to offer :

<li>Cloud Firestore</li>
<li>Cloud Functions</li>
<li>CDN Hosting</li>
<li>Authentication</li>
<li>Firebase Cloud Messaging</li>

The point being is that Firebase is a fantastic resource to power start your development 🚀 

![fry](https://dev-to-uploads.s3.amazonaws.com/i/m3yyos5lohoumv5pjuuj.jpg)

<figcaption>Too real.. or way too real</figcaption>


I first stumbled across Firebase when a few university friends were speaking to me about an app idea they were developing. My first question to them was, how are you going to handle the [IAM](https://en.wikipedia.org/wiki/Identity_management)? From previous experience, I know a full IAM system can be burdening to a new developing venture. In the age of sophisticated crypto attacks, salted hashes and privacy concerns *cough* GDPR *cough* - it's a headache to say the least. I googled ways in which other apps were solving this problem, especially with easy social sign-ins and Firebase Authentication was the answer. 

Slightly on a tangent, this is where as Cloud technologies are becoming so powerful, it empowers developers to do what they actually enjoy doing - which is burning out code 🔥. Gone are the days where you would have to worry about maintaining a database or UNIX box with security patches, or architecting an entire development environment before you even get to experiment with different technologies. 

<b>Innovation occurs most often when those that can ask the right questions, have the best opportunity to answer.<b>

Back to Firebase and IAM, Firebase provides a simple entry point to Authenticating users with a wide variety of options, including Facebook, Twitter, Apple etc. 

![Over here ](https://dev-to-uploads.s3.amazonaws.com/i/442r4inhcmgsxay6pfxa.png)

<figcaption>A full list of Authentication providers at time of writing</figcaption>

So, how does it all piece together? 

Firebase has a client side library which allows a user to enter their credentials, with one of the enabled providers above, and if successful, return a Firebase token. This Firebase token is a [JWT](https://jwt.io/). We can use this token to identify the user to calls made to the back end. 

Note : Pre-requisite for using Firebase, is signing up for an account. 

We now need to install the Firebase SDK in a preferred server-side language. We can choose from Node.JS, Java, Python, Go & C#. If your favourite language isn't here, you can always use the implementation described [here](https://firebase.google.com/docs/auth/admin/verify-id-tokens).

In Java, initialising the application would like somewhat like this : 

```java
	/**
	 * Initialises Firebase connection.
	 * 
	 * @throws IllegalStateException if application can't be initialised.
	 */
	@PostConstruct
	public void initialiseFirebase() {
		try {
			FileInputStream serviceAccount = new FileInputStream(firebaseCredentials);
			FirebaseOptions options = new FirebaseOptions.Builder()
					.setCredentials(GoogleCredentials.fromStream(serviceAccount))
					.setDatabaseUrl("https://****.firebaseio.com").build();

			FirebaseApp.initializeApp(options);
		} catch (IOException e) {
			throw new IllegalStateException("Unable to initalise Firebase Application", e);
		}
	}
```

Maven dependency : 

```java
		<dependency>
			<groupId>com.google.firebase</groupId>
			<artifactId>firebase-admin</artifactId>
			<version>6.12.2</version>
		</dependency>
```

With the use of [provided methods](https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/auth/FirebaseAuth), we can pass in the token, which will then be verified of structure and expiration etc. We can decode the token, retrieve the UUID of our user and call more information if needed. For example, a user's email address as below - all of this through the SDK! 

```java
	/**
	 * If the provided ID token has the correct format, is not expired, and is
	 * properly signed, the method returns the decoded UUID.
	 * 
	 * @param idToken
	 * @return {@code String} Firebase UUID
	 */
	public String getFirebaseDecodedUid(String idToken) {
		try {
			FirebaseToken decodedToken = getFirebaseToken(idToken);
			return decodedToken.getUid();
		} catch (IllegalArgumentException e) {
			throw new NotAuthorizedException("Unable to read authentication client side token.", e);
		}
	}

	/**
	 * Returns email of a user by their Firebase UUID.
	 * 
	 * @param firebaseId
	 * @return {@code String}
	 */
	public String getUser(String firebaseId) {
		try {
			return FirebaseAuth.getInstance().getUser(firebaseId).getEmail();
		} catch (FirebaseAuthException e) {
			throw new InternalServerErrorException("Unable to return user", e);
		}
	}

```


We have successfully found a way to authenticate users with little hassle, so we can focus on writing application logic. 

Firebase has a whole arsenal of functionality to explore, this is a small look into what a powerful platform it can be.

The next logical phase once users are authenticated is how can you differentiate and authorise them to the right back-end calls. That's for another day and another blog post.