DEV Community

Cover image for Let’s touch base.. with Firebase 🔥
Ali Zaidi
Ali Zaidi

Posted on

Let’s touch base.. with Firebase 🔥

To put it mildly, Firebase is a beast.

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 :

  • Cloud Firestore

  • Cloud Functions

  • CDN Hosting

  • Authentication

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

    fry

    Too real.. or way too real

    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? 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.

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

    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

    A full list of Authentication providers at time of writing

    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. 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.

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

        /**
         * 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);
            }
        }
    
    Enter fullscreen mode Exit fullscreen mode

    Maven dependency :

            <dependency>
                <groupId>com.google.firebase</groupId>
                <artifactId>firebase-admin</artifactId>
                <version>6.12.2</version>
            </dependency>
    
    Enter fullscreen mode Exit fullscreen mode

    With the use of provided methods, 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!

        /**
         * 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);
            }
        }
    
    
    Enter fullscreen mode Exit fullscreen mode

    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.

    Top comments (2)

    Collapse
     
    dillan1994 profile image
    dillan1994

    Nice post! What are your opinions on using Firebase authentication vs say, just requiring the user to authenticate via popular options such as Google, Twitter, etc.

    Collapse
     
    azaidi93 profile image
    Ali Zaidi

    So Firebase can be used as a wrapper of sorts over several authentication options so I would think this gives the long term architecture of your application some strength 👍🏽