Skip to content

Getting Started with Firebase Authentication on Android

Although I have covered using Firebase Authentication with FirebaseUI, I figured I haven’t covered the traditional way of implementing Firebase Authentication which allows you to use your own authentication screen.

Back to the basics! This one is going to be quick and easy. You don’t want to waste time reading useless jargain and I don’t particularly feel like spending too long today on this. Let’s get to it.

This will cover how to perform Firebase Auth operations like signing in, signing up, and logging out. I assume you know how to make a UI with an EditText and a listener on it so none of that here.

Import the Dependency

implementation 'com.google.firebase:firebase-auth:16.0.2'

Add this to your app-level build.gradle file.

Initialise FirebaseAuth

private FirebaseAuth mAuth = FirebaseAuth.getInstance();

If you try to do anything before initialising, crash goes your app.

Get Current User and User ID

FirebaseUser currentUser = mAuth.getCurrentUser();
String uid = currentUser.getUid();

These are the bread and butter methods of authentication: getting your user and his UID to use in the database, cloud messaging, or other stuff. If your user isn’t signed in, both of these will simply return null.

Signing Up New Users

Firebase Authentication allows you to use different authentication providers in your app. In the Firebase Console > Authentication > Sign-in Method, enable the providers you intend to use. (Note that for each, different setup will be required).

For now, we’ll only cover the standard email-password authentication provider. If you want me to cover how to authenticate with other providers like Facebook and Google, leave it in the comments.

mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "createUserWithEmail:success");
                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "createUserWithEmail:failure", task.getException());
                    Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }

                // ...
            }
        });

Code snippet taken from the Firebase docs

Add this method to your submit button’s onClickListener or something. You pass in an email and password and I’m sure you can guess the rest.

Sign in Existing Users

Once again, this is just for the standard email-password provider.

mAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "signInWithEmail:success");
                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "signInWithEmail:failure", task.getException());
                    Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }

                // ...
            }
        });

Same story as signing up. You got the method, pass in the email and password and Firebase does the magic with callbacks for you to do your stuff when Firebase is done doing its stuff.

Accessing User Information

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // Name, email address, and profile photo Url
    String name = user.getDisplayName();
    String email = user.getEmail();
    Uri photoUrl = user.getPhotoUrl();

    // Check if user's email is verified
    boolean emailVerified = user.isEmailVerified();

    // The user's ID, unique to the Firebase project. Do NOT use this value to
    // authenticate with your backend server, if you have one. Use
    // FirebaseUser.getIdToken() instead.
    String uid = user.getUid();
}

Code snippet taken from the Firebase docs

Once your user is signed in and the current user won’t be null, you can access information you’ll need to deliver a good app experience.