How to implement Firebase Authentication in Android (Example code)
Please Subscribe Youtube| Like Facebook | Follow Twitter
For Kotlin follow this article
Introduction
In this article we will learn how to use firebase authentication in our app. You can use it to identify user in your application. Firebase Authentication provides various Sign-in providers through which you can authenticate user such as Anonymous, Email/Password, Google and Facebook etc. Firebase Auth uses user’s uid to uniquely identify user. Firebase store authentication info in its cache so once user is authenticated then authentication will work offline as well.
In Anonymous provider you can sign-in user anonymously which allows user to create temporary account to authenticate without providing details i.e username, password, email etc. Keep in mind that if user sign-in using Anonymous Sign-in method and if user clears app data then previous Anonymous Authentication user’s uid will be lost and new user’s uid will be generated in Anonymous Signing-in again. However using other Sign-in providers method if app data is cleared then same uid and user details will be restored by again signing-in using same account. You can also convert an anonymous account to a permanent account later if required.
Our Example
In our example we have textview which shows current login user details and button which allows user to authenticate using Anonymous, Email/Password or Google Sign-in providers. On app start we will check if user is not signed-in then we will display button which will authenticate user and if user is already signed in then we will display user details on textview.
Requirements:
- Android Project/App in which authentication to be implemented
- Firebase Project
Note: First you need to create Firebase Project and then connect your app to it. You can follow this article to set it up.
Steps
Follow below steps
1) Enable sign-in provider in Firebase Authentication
2) Code Authentication Logic
3) Run and test your app
1) Enable sign-in provider in Firebase Auth
First go to Firebase and open your Firebase Project and click on Authentication.
Click on setup sign-in method
Enable Email/Password, Google and Anonymous providers
2) Code Authentication Logic
First add firebase-auth and firebase-ui-auth library at app level build.gradle file
implementation 'com.google.firebase:firebase-auth:19.3.1'
implementation 'com.firebaseui:firebase-ui-auth:6.2.0'
Application screen contains textview and button below is layout file code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center"
>
<TextView
android:id="@+id/user_details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
/>
<Button
android:id="@+id/authenticate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Authenticate"
android:visibility="gone"
android:onClick="authenticate"
/>
</RelativeLayout>
On app start we have called checkSigInStatus() method which will check if user is signed-in then display user details else display authentication button to authenticate user.
private void checkSigInStatus() {
authUser = FirebaseAuth.getInstance().getCurrentUser();
if(authUser!=null){
userDetails.setText("Current Logged in User\nUser Id = "+authUser.getUid()+"\n"
+ "User Name = "+authUser.getDisplayName()+"\n"
+ "Email = "+authUser.getEmail());
authenticate.setVisibility(View.GONE);
userDetails.setVisibility(View.VISIBLE);
}
else{
userDetails.setVisibility(View.GONE);
authenticate.setVisibility(View.VISIBLE);
}
}
On authenticate button click we will display authentication screen to user to authenticate using Anonymous, Email/Password, Google providers. Result of Authentication will be reported inside onActivityResult() method, we have passed result code RC_SIGN_IN=1. Add FirebaseTheme inside res->values->styles.xml
<style name="FirebaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
public void authenticate(View view) {
// Choose authentication providers
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.AnonymousBuilder().build(),
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build()
);
// Create and launch sign-in intent
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setTheme(R.style.FirebaseTheme)
.build(),
RC_SIGN_IN);
}
onActivityResult() method we have checked if authentication is successful then display user details else toast Sign in Failed message.
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK && FirebaseAuth.getInstance().getCurrentUser()!=null ) {
//display logged in user info
checkSigInStatus();
} else {
Toast.makeText(this,"Sign in Failed. Please Sign in To Continue",Toast.LENGTH_SHORT).show();
}
}
}
Whole Code
App level build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 28
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.programtown.example"
minSdkVersion 17
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'com.google.firebase:firebase-auth:19.3.1'
implementation 'com.firebaseui:firebase-ui-auth:6.2.0'
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center"
>
<TextView
android:id="@+id/user_details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
/>
<Button
android:id="@+id/authenticate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Authenticate"
android:visibility="gone"
android:onClick="authenticate"
/>
</RelativeLayout>
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="FirebaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
</resources>
MainActivity.java
package com.programtown.example;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
FirebaseUser authUser;
private static final int RC_SIGN_IN = 1;
TextView userDetails;
Button authenticate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userDetails= (TextView) findViewById(R.id.user_details);
authenticate= (Button) findViewById(R.id.authenticate);
checkSigInStatus();
}
private void checkSigInStatus() {
authUser = FirebaseAuth.getInstance().getCurrentUser();
if(authUser!=null){
userDetails.setText("Current Logged in User\nUser Id = "+authUser.getUid()+"\n"
+ "User Name = "+authUser.getDisplayName()+"\n"
+ "Email = "+authUser.getEmail());
authenticate.setVisibility(View.GONE);
userDetails.setVisibility(View.VISIBLE);
}
else{
userDetails.setVisibility(View.GONE);
authenticate.setVisibility(View.VISIBLE);
}
}
public void authenticate(View view) {
// Choose authentication providers
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.AnonymousBuilder().build(),
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build()
);
// Create and launch sign-in intent
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setTheme(R.style.FirebaseTheme)
.build(),
RC_SIGN_IN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK && FirebaseAuth.getInstance().getCurrentUser()!=null ) {
//display logged in user info
checkSigInStatus();
} else {
Toast.makeText(this,"Sign in Failed. Please Sign in To Continue",Toast.LENGTH_SHORT).show();
}
}
}
}
3) Run and test your app
First authenticating using Anonymous method (continue as guest). In this method only user’s uid will be shown after authentication.
Now clearing apps data and then authenticating using email/password (Sign in with email) method, after authentication user name and email will be displayed on screen.
After authentication clear apps data and sign in again using email by providing previous account email and password. After signing in account information will be restored.
In user tab you can see list of registered users
Conclusion
So in this post we have learned how to implement Firebase Authentication in android application to identify/authenticate user.
Please Subscribe Youtube| Like Facebook | Follow Twitter