Developer AdvocateWhen Firebase Auth launched at Google I/O 2016, it allowed your users to create an account on your app where they signed in with an email address and a password. But this email address could be anything -- as it wasn't linked to the actual account through a verification process: so, for example, your users could identify themselves as [celebrity name]@[anydomain] if they wanted to.
To solve this problem, Email Verification has been added to Firebase Auth -- where, in the above case, Firebase will send an email to that address containing a validation link. So if that celebrity really is signing up for your app, he'll get the link and click on it. You can check to see if the account is verified at sign in, and take an action in response -- such as blocking them from signing in.
When you run the app, and select the Email/Password authentication activity, you'll see this screen, where it gives you the option to sign in (if you have an account already), or create one (if you don't).
When you click the 'Create Account' button, you'll get taken to a new activity, showing the user identity, and the Firebase User ID associated with it. You'll also see that the email isn't verified, with a button allowing you to verify it:
Clicking the Verify Email button will then send an email to that address. This email will contain a link, and once the user clicks on that link, the account will be verified.
This email is shown on the Email Templates tab in the Authentication section of the Firebase console. From here you can edit the action link, or the reply address so that it appears to be from your domain, instead of authui-xxxx.firebaseapp.com as shown above.
Here you can see what happens once the account is verified and I sign in again.
You'll also see that this identity is present as a user in the Firebase console. You can manage them from there -- including changing their password or removing them from your app altogether.
Coding for Email Verification
Details on coding for email verification can be found in the Manage Users section of the Firebase documentation (Android, iOS, Web). For the rest of this post, I'll be looking at the Android code, but the implementation on the other platforms is very similar.
The core functionality is found on the FirebaseUserobject. On it is a sendEmailVerification() method, which returns as Taskused to asynchronously send the email, and report on the status. If the task is successful, you know the email was sent. Here's an example:
final FirebaseUser user = mAuth.getCurrentUser(); user.sendEmailVerification() .addOnCompleteListener(this, new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { // Re-enable button findViewById(R.id.verify_email_button).setEnabled(true);
if (task.isSuccessful()) { Toast.makeText(EmailPasswordActivity.this, "Verification email sent to " + user.getEmail(), Toast.LENGTH_SHORT).show(); } else { Log.e(TAG, "sendEmailVerification", task.getException()); Toast.makeText(EmailPasswordActivity.this, "Failed to send verification email.", Toast.LENGTH_SHORT).show(); } } });
In this case, the user is retrieved from mAuth.getCurrentUser(), and the sendEmailVerification() method is called on it. This gets Firebase to send the mail -- and if the task was successful, you'll see that a toast will pop up showing that it happened. After the user clicks the link in the email, subsequent calls to user.isEmailVerified()will return true. Here's how it is used in the sample app:
Do note that the FirebaseUser object is cached within an app session, so if you want to check on the verification state of a user, it's a good idea to call .getCurrentUser().reload() for an update.
In the sample app it just shows on the activity if the user's email address is verified or not. For your app you could limit functionality based on this state -- even to the extent of denying them access to the signed in section of the app.
You can learn more about Firebase Auth, including sign-in with other providers such as Google, Facebook, Twitter and more on the Firebase developers site.
Developer AdvocateFirebase Auth is a secure authentication system that allows users to sign up and sign in for your application. It allows you to use federated identity through providers, such as Facebook, Twitter, and of course - Google. When doing this, your users will demand a rich user experience, and the burden of implementing this will fall on you as a developer. In addition, creating apps that allow for sign in involves a lot more than just signing in -- there are many other user flows, such as choosing from multiple accounts, signing up for new accounts, resetting passwords and more. This can be a lot of work!
Luckily, the open-source FirebaseUI libraries make all of this really easy. In this post, you'll take a look at building a simple web site that allows for sign in and sign up. You'll use two providers: The built-in Email/Password on Firebase, and federated identity using Google Sign-In.
Getting Started
To use FirebaseUI, you need a Firebase app or site, and you created these on the Firebase Console. From here, select 'Authentication' on the left (1).
When you select 'Sign-In Method' at the top, you'll be given a list of Sign-in providers. Choose 'Email/Password' and 'Google' (2). Make sure they're enabled.
Additionally, if you are going to host these pages on your own domain, make sure the domain is added to the list of OAuth redirect domains at the bottom of the screen. (3).
Now, back on the Overview screen for your project, click 'Add Firebase to your Web app', and you'll see a popup like this:
This contains all the code you need to initialize Firebase on your web site. Let's take a look at a simple 2-page web site next: one page for signing in, and one page for after you've signed in.
A simple site with Sign In
I've built and hosted a simple site using FirebaseUI Auth here. The first page you see when you go to this site looks like this:
As you can see, it's pretty straightforward, with two sign-in options -- Google and Email, matching what we configured in the Firebase console.
Clicking Sign-In with Google can have multiple effects based on the context:
If you've signed in previously on this browser, you'll be taken straight back into the site
If you have multiple Google accounts, you'll be given the account chooser, with the choice to pick a different account, or create a new one, like this:
If you haven't signed in on this browser, and don't have a Google account, you'll be given the option to enter one, or create a new one, like this:
Clicking on the Create account link will take you through the standard user flow for creating an account, which will return you to your site to sign in when you're done.
Similarly when using Email/Password auth, you'll get the full user flow.
If you've signed in with an Email/Password combination before, and you're the only user, you'll go straight into the site.
If you've signed in with an Email/Password combination before, but aren't the only user, you'll get a list of accounts to choose from, like this:
This also gives you the facility to add a new account, and doing so creates a new account on firebase that you can use to sign in in future. There are many scenarios, with a very complex flow. To see a detailed flowchart of these, click here.
So let's look at the code needed to implement this!
Coding the Log In Page
Here's the full source code for the Log In page you've seen in this post. You'll see that there are two highlighted blocks. The first is the initialization code that you got from the Firebase console earlier. The second uses the FirebaseUI open source code to create the user interface widgets.
The things to note in the second block are the signInSuccessUrl parameter, which is the address of the page to redirect to once the sign in is successful. Also, note the signInOptions setting where Google Sign-In and Email Sign-In are configured.
<!DOCTYPE html> < html lang="en"> < head> < title>EasyAuth</title> <meta charset="UTF-8"> </head> <!-- Below is the initialization snippet for my Firebase project. It will vary for each project --> <script src="https://www.gstatic.com/firebasejs/3.6.4/firebase.js"></script> <script> // Initialize Firebase var config = { apiKey: "AIzaSyAPtNmUso5tA8d83vaJlgDHA_4C7HEgYNY", authDomain: "authui-6818f.firebaseapp.com", databaseURL: "https://authui-6818f.firebaseio.com", storageBucket: "authui-6818f.appspot.com", messagingSenderId: "596916061379" }; firebase.initializeApp(config); </script> <!-- The code below initializes the sign-in widget from FirebaseUI web. --> <script src="https://cdn.firebase.com/libs/firebaseui/1.0.0/firebaseui.js"></script> <link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/1.0.0/firebaseui.css" /> <script type="text/javascript"> var uiConfig = { signInSuccessUrl: 'loggedIn.html', signInOptions: [ // Specify providers you want to offer your users. firebase.auth.GoogleAuthProvider.PROVIDER_ID, firebase.auth.EmailAuthProvider.PROVIDER_ID ], // Terms of service url can be specified and will show up in the widget. tosUrl: '<your-tos-url>' }; // Initialize the FirebaseUI Widget using Firebase. var ui = new firebaseui.auth.AuthUI(firebase.auth()); // The start method will wait until the DOM is loaded. ui.start('#firebaseui-auth-container', uiConfig); </script> <!-- Include a simple background image & and title --> <div></div> <body> <h1 align="center" style="color:white;">Firebase Auth Quickstart Demo</h1> <div id="firebaseui-auth-container"></div> </body> </html>
Note that this is all the code you need to implement to get the user flows mentioned earlier. Everything is encapsulated in the open source library.
The Signed-In page will need the first block of code in order to ensure that it uses Firebase, and then, when the firebase.auth().onAuthStateChanged event fires, you know the user is signed in, and you can query their exposed metadata.
Here's the code:
<!DOCTYPE html> <html lang="en"> <head> <title>EasyAuth</title> <meta charset="UTF-8"> </head> <!-- Below is the initialization snippet for my Firebase project. It will vary for each project --> <script src="https://www.gstatic.com/firebasejs/3.6.4/firebase.js"></script> <script> // Initialize Firebase var config = { apiKey: "AIzaSyAPtNmUso5tA8d83vaJlgDHA_4C7HEgYNY", authDomain: "authui-6818f.firebaseapp.com", databaseURL: "https://authui-6818f.firebaseio.com", storageBucket: "authui-6818f.appspot.com", messagingSenderId: "596916061379" }; firebase.initializeApp(config); </script> <body> <!-- A simple example script to add text to the page that displays the user's Display Name and Email --> <script> // Track the UID of the current user. var currentUid = null; firebase.auth().onAuthStateChanged(function(user) { // onAuthStateChanged listener triggers every time the user ID token changes. // This could happen when a new user signs in or signs out. // It could also happen when the current user ID token expires and is refreshed. if (user && user.uid != currentUid) { // Update the UI when a new user signs in. // Otherwise ignore if this is a token refresh. // Update the current user UID. currentUid = user.uid; document.body.innerHTML = '<h1> Congrats ' + user.displayName + ', you are done! </h1> <h2> Now get back to what you love building. </h2> <h2> Need to verify your email address or reset your password? Firebase can handle all of that for you using the email you provided: ' + user.email + '. <h/2>'; } else { // Sign out operation. Reset the current user UID. currentUid = null; console.log("no user signed in"); } }); </script> <h1>Congrats you're done! Now get back to what you love building.</h1> </html>
And that's it! Hopefully this primer will help you understand the power that you get with the FirebaseUI Auth libraries, and how they make it much easier for you to build web apps that sign in!
With Firebase, we've been working towards a world where developers don't have to deal with managing servers and can instead build web and mobile apps with only client-side code. However, there are times when you really do need to spin up your own server. For example, you may want to integrate with a third-party API (such as an email or SMS service), complete a computationally expensive task, or have a need for a trusted actor. We want to make your experience on this part of your stack as simple as it is on the front-end. Towards that aim, we announced the Firebase Admin SDKs for Node.js and Java at the Firebase Dev Summit in Berlin earlier this week.
What are the Admin SDKs?
The Firebase Admin SDKs provide developers with programmatic, second-party access to Firebase services from server environments. Second-party here refers to the fact that the SDKs are granted elevated permissions that allow them to do more than a normal, untrusted client device can. The Admin SDKs get these elevated permissions since they are authenticated with a service account, a special Google account that can be used by applications to access Google services programmatically. The Admin SDKs are meant to complement the existing Firebase web and mobile clients which provide third-party, end-user access to Firebase services on client devices.
Some of this may sound familiar for those of you who have used the existing Firebase Node.js and Java SDKs. The difference is that we have now split the second-party (aka "admin") and third-party (aka "end-user") access use cases into separate SDKs instead of conflating them together. This should make it easier for beginners and experts alike to know which SDK to use and which documentation to follow. It also allows us to tailor the Admin SDKs towards server-specific use cases. A great example of this is the new user management auth API which we will go into in the next section.
What can the Admin SDKs do?
The Admin SDKs for Node.js and Java offer the following admin capabilities that already existed in the prior server SDKs:
In addition, the Node.js SDK brings some exciting new functionality:
Admin API for managing Firebase Auth users, including the ability to fetch user data, create new users, update user properties, and delete users. You can do all of this without a user's existing password and without worrying about rate limiting. This has been a heavily requested feature from developers for years now and we are excited to finally put it into your hands.
The best place to start is with our Admin SDKs setup guide. The guide will walk you through how to download the SDK, generate a service account key file, and use that key file to initialize the Admin SDK. Thanks to our new Service Accounts panel in your Firebase Console settings, generating service account keys should be a breeze.
What's next for the Admin SDKs?
This is really just the beginning for the Admin SDKs. We plan to expand the Admin SDKs across two dimensions. Firstly, we want to provide Admin SDKs in more programming languages, allowing you to write code in the language you feel most comfortable. Secondly, we plan to integrate with more Firebase services, including adding support for services like Firebase Cloud Messaging and bringing the new user management API to Java.
Would you like us to build an Admin SDK in a particular language? Do you want the Admin SDKs to support a certain Firebase service or feature? Let us know in the comments below or by sending us a note through our feature request support channel.
We are excited to expand our first-class support for backend developers in the Firebase ecosystem. Stay tuned for more to come in the future!
For most developers, building an authentication system for your app can feel a lot like paying taxes. They are both relatively hard to understand tasks that you have no choice but doing, and could have big consequences if you get them wrong. No one ever started a company to pay taxes and no one ever built an app just so they could create a great login system. They just seem to be inescapable costs.
But now, you can at least free yourself from the auth tax. With Firebase Authentication, you can outsource your entire authentication system to Firebase so that you can concentrate on building great features for your app. Firebase Authentication makes it easier to get your users signed-in without having to understand the complexities behind implementing your own authentication system. It offers a straightforward getting started experience, optional UX components designed to minimize user friction, and is built on open standards and backed by Google infrastructure.
Implementing Firebase Authentication is relatively fast and easy. From the Firebase console, just choose from the popular login methods that you want to offer (like Facebook, Google, Twitter and email/password) and then add the Firebase SDK to your app. Your app will then be able to connect securely with the real time database, Firebase storage or to your own custom back end. If you have an auth system already, you can use Firebase Authentication as a bridge to other Firebase features.
Firebase Authentication also includes an open source UI library that streamlines building the many auth flows required to give your users a good experience. Password resets, account linking, and login hints that reduce the cognitive load around multiple login choices - they are all pre-built with Firebase Authentication UI. These flows are based on years of UX research optimizing the sign-in and sign-up journeys on Google, Youtube and Android. It includes Smart Lock for Passwords on Android, which has led to significant improvements in sign-in conversion for many apps. And because Firebase UI is open source, the interface is fully customizable so it feels like a completely natural part of your app. If you prefer, you are also free to create your own UI from scratch using our client APIs.
And Firebase Authentication is built around openness and security. It leverages OAuth 2.0 and OpenID Connect, industry standards designed for security, interoperability, and portability. Members of the Firebase Authentication team helped design these protocols and used their expertise to weave in latest security practices like ID tokens, revocable sessions, and native app anti-spoofing measures to make your app easier to use and avoid many common security problems. And code is independently reviewed by the Google Security team and the service is protected in Google’s infrastructure.
Fabulous use Firebase Auth to quickly implement sign-in
Fabulous uses Firebase Authentication to power their login system. Fabulous is a research-based app incubated in Duke University’s Center for Advanced Hindsight. Its goal is to help users to embark on a journey to reset poor habits, replacing them with healthy rituals, with the ultimate goal of improving health and well-being.
The developers of Fabulous wanted to implement an onboarding flow that was easy to use, required minimal updates, and reduced friction with the end user. They wanted an anonymous option so that users could experiment with it before signing up. They also wanted to support multiple login types, and have an option where the user sign-in flow was consistent with the look and feel of the app.
“I was able to implement auth in a single afternoon. I remember that I spent weeks before creating my own solution that I had to update each time the providers changed their API” - Amine Laadhari, Fabulous CTO.
Malang Studio cut time-to market by months using Firebase Auth
Chu-Day is an application (available on Android and iOS) that helps couples to never forget the dates that matter most to them. It was created by the Korean firm Malang Studio, that develops character-centric, gamified lifestyle applications.
Generally, countdown and anniversary apps do not require users to sign-in, but Malang Studio wanted to make Chu-day special, and differentiate it from others by offering the ability to connect couples so they could jointly countdown to a special anniversary date. This required a sign-in feature, and in order to prevent users from dropping out, Chu-day needed to make the sign-in process seamless.
Malang Studio was able to integrate an onboarding flow in for their apps, using Facebook and Google Sign-in, in one day, without having to worry about server deployment or databases. In addition, Malang Studio has also been taking advantage of the Firebase User Management Console, which helped them develop and test their sign-in implementation as well as manage their users:
“Firebase Authentication required minimum configuration so implementing social account signup was easy and fast. User management feature provided in the console was excellent and we could easily implement our user auth system.” - Marc Yeongho Kim, CEO / Founder from Malang Studio