Android – Getting started with Firebase: User Authentication
Firebase was established by Andrew Lee and James Tamplin back in 2011 yet was launched formally in April 2012. Initially, the framework was expected to be a real-time database giving its APIs, enabling users to store and synchronize information across various customers. Now, it’s grown into a dozen of developer products that provide a platform for developing, marketing and monetizing native and web based mobile applications.
It provides you with a set of authentication options out-of-the-box: it automatically stores your users’ credentials securely and redundantly. So it separates sensitive user credentials from your application data, and lets you focus on the user interface and experience for your app.
In this tutorial we will build a simple login/signup demo using the Firebase Email & Password authentication.
Firebase ?
Firebase comes with a set features from the very basic like authentication to app hosting, offering realtime databases and crush reporting. Firebase can now be seen as the glue that brings together so many of Google’s offerings. With Firebase, analytics are now free and built-in. Ads can also be easily taken advantage of. All of this from a single SDK, with a single dashboard. This is a lot of time to save i guess !
Why should you opt for Firebase ?
• using firebase, you wont need no server side configuations, php scripts, or database designs.
• it’s easy and quick to implement.
• robust APIs for Javascript (including several frameworks like Angular), iOS, and Android.
• built-in support for authentication services like Facebook, Google, and Twitter.
• you can start using it for free (you only need to pay of your app hits 50 connections).
And Why not ?
• Implementation of REST API could be difficult on embedded platforms.
• Data validation rules do not support complex objects directly (you’d need to validate individual child nodes separately).
• Storage format is entirely different from that of SQL, (Firebase uses JSON) so you wouldn’t be able to migrate that easily.
Enabling Firebase Authentication
1- First thing you need is to access your Firebase console. To do so, create an account on https://firebase.google.com/ then create you first project. Beaware to give the package name of your project, as you’ll be working on it.
2- In your project’s dashboard, go to Authentication, then sign-in method and enable the Email/Password authentication.
Now you are ready to start your android project. Keep the google-services.json file you just got and move on to Android Studio !
You will need to set some configuration before starting:
– add the INTERNET permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
– paste the google-services.json file to your project’s app folder. Beaware not to skip this step. Your project won’t build without this file?
– add the firebase dependency to the build.gradle located in project’s home directory:
dependencies { classpath 'com.android.tools.build:gradle:2.1.2' classpath 'com.google.gms:google-services:3.0.0' }
– add apply plugin: ‘com.google.gms.google-services’ to project/build.gradle :
dependencies { compile "com.google.firebase:firebase-auth:9.0.2" } apply plugin: 'com.google.gms.google-services'
Now we have the project ready with all the dependencies added. Let’s start by adding the sign up screen.
Sign up with email and password
Let’s make the default activity_main.xml our signup ui :
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.androidprojects.esprit.firebaselogin.MainActivity"> <EditText android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Email" android:inputType="textEmailAddress" android:maxLines="1" android:singleLine="true" /> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:focusableInTouchMode="true" android:hint="Password" android:imeActionId="@+id/login" android:imeOptions="actionUnspecified" android:inputType="textPassword" android:maxLines="1" android:singleLine="true" /> <Button android:id="@+id/sign_up_button" style="?android:textAppearanceSmall" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:background="@color/colorAccent" android:text="Register" android:textColor="@android:color/black" android:textStyle="bold" /> <Button android:id="@+id/btn_reset_password" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dip" android:background="@null" android:text="Forgot password?" android:textAllCaps="false" android:textColor="@color/colorAccent" /> <Button android:id="@+id/sign_in_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dip" android:background="@null" android:text="Already registered. Login me" android:textAllCaps="false" android:textColor="@color/colorAccent" android:textSize="15dp" /> <ProgressBar android:id="@+id/progressBar" android:layout_width="30dp" android:layout_height="30dp" android:layout_gravity="center|bottom" android:layout_marginBottom="20dp" android:visibility="gone" /> </LinearLayout>
In the MainActivity.java, under the btnSignUp.setOnClickListener(), we’ll use the createUserWithEmailAndPassword() method from the FirebaseAuth object, to create a new user with email and password data:
public class MainActivity extends Activity { private EditText inputEmail, inputPassword; private Button btnSignIn, btnSignUp, btnResetPassword; private ProgressBar progressBar; private FirebaseAuth auth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnSignIn = (Button) findViewById(R.id.sign_in_button); btnSignUp = (Button) findViewById(R.id.sign_up_button); inputEmail = (EditText) findViewById(R.id.email); inputPassword = (EditText) findViewById(R.id.password); btnResetPassword = (Button) findViewById(R.id.btn_reset_password); progressBar = (ProgressBar) findViewById(R.id.progressBar); //Get Firebase auth instance auth = FirebaseAuth.getInstance(); btnSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { progressBar.setVisibility(View.VISIBLE); auth.createUserWithEmailAndPassword(inputEmail.getText().toString(),inputPassword.getText().toString()) .addOnCompleteListener(MainActivity.this, new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { Toast.makeText(MainActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.GONE); if (!task.isSuccessful()){ Toast.makeText(MainActivity.this, "Authentication failed." + task.getException(), Toast.LENGTH_SHORT).show(); } else{ startActivity(new Intent(MainActivity.this, HomeActivity.class)); finish(); } } }); } }); btnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (TextUtils.isEmpty(inputEmail.getText().toString())) { Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(inputPassword.getText().toString())) { Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show(); return; } startActivity(new Intent(MainActivity.this, LoginActivity.class)); } }); btnResetPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } @Override protected void onResume() { super.onResume(); progressBar.setVisibility(View.GONE); } }
If you run your app and login to Firebase console, you can see the user created with the email you have given the android app:
Login with email and password
Your login layout will be similar to the signup’s layout: email and password textviews with a login.. ( certain description to avoid re-writing the same code )
Firebase provides signInWithEmailAndPassword() method to sign in the user. We’ll call it on the btnLogin click:
btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String email = inputEmail.getText().toString(); final String password = inputPassword.getText().toString(); if (TextUtils.isEmpty(email)) { Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(password)) { Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show(); return; } progressBar.setVisibility(View.VISIBLE); auth.signInWithEmailAndPassword(email,password) .addOnCompleteListener(LoginActivity.this, new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { progressBar.setVisibility(View.GONE); if (!task.isSuccessful()) { Toast.makeText(LoginActivity.this, "Login failed! Invalid email or password,\nPlease try agin.", Toast.LENGTH_LONG).show(); } else { startActivity(new Intent(LoginActivity.this, HomeActivity.class)); finish(); } } }); } });
Send password reset email
In our mainActivity.java, under the btnResetPassword.setOnClickListener, we’ll simply call the sendPasswordResetEmail() method:
btnResetPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //startActivity(new Intent(MainActivity.this, ResetPasswordActivity.class)); String email = inputEmail.getText().toString().trim(); if (TextUtils.isEmpty(email)) { Toast.makeText(getApplication(), "Enter your registered email id", Toast.LENGTH_SHORT).show(); return; } progressBar.setVisibility(View.VISIBLE); auth.sendPasswordResetEmail(email) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { Toast.makeText(MainActivity.this, "We have sent you instructions to reset your password!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Failed to send reset email!", Toast.LENGTH_SHORT).show(); } progressBar.setVisibility(View.GONE); } }); } });
You can change the email’s content from your firebase console going to Authentication then Email templates:
Sign out
Signing your user out is as simple as calling the FirebaseAuth.signOut() method
auth.signOut(); // this listener will be called when there is change in firebase user session FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user == null) { startActivity(new Intent(MainActivity.this, LoginActivity.class)); finish(); } } };
You might also need to check wether user is connected or not, update password or email, and/or delete user.
Update password/email
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); user.updatePassword(newPassword.getText().toString().trim()) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { Toast.makeText(MainActivity.this, "Password is updated!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Failed to update password!", Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.GONE); } } }); user.updateEmail(newEmail.getText().toString().trim()) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { Toast.makeText(MainActivity.this, "Email address is updated.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "Failed to update email!", Toast.LENGTH_LONG).show(); } } });
Delete user
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { user.delete() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { Toast.makeText(MainActivity.this, "Your profile is deleted:( Create a account now!", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Failed to delete your account!", Toast.LENGTH_SHORT).show(); } } }); }
Check user session
auth = FirebaseAuth.getInstance(); if (auth.getCurrentUser() != null) { // User is logged in }
That’s all coders ! And yes, firebase is that simple and easy to use. We’ll keep on discovering the firebase SDK in coming tutorials. You can get the code for this one here. Happy coding !
Recent Comments