Google Authentication using Firebase in Android
In this blog post, we are going to learn how to use Google authentication using firebase in android.
Most apps want to know the identity of a user. Knowing a user’s identity allows an app to securely save user data in the cloud and provide the same personalized experience across all of the user’s devices.
Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.
But today we will discuss the Firebase Google authentication service. You can let your users authenticate with Firebase using their Google Accounts by integrating Google Sign-In into your app.
Overview
Before begin
- If you haven’t already, add Firebase to your Android project.
- Declare the dependency for the Firebase Authentication Android library in your module (app-level) Gradle file (usually app/build.gradle).
- Also, as part of setting up Firebase Authentication, you need to add the Google Play services SDK to your app.
- Enable Google Sign-In in the Firebase console:
- In the Firebase console, open the Auth section.
- On the Sign-in method tab, enable the Google sign-in method and click Save.
Design our Layout
- Create a button for the Google Sign-In
<Button android:id=”@+id/google_signIn_btn” android:layout_width=”match_parent” android:layout_height=”wrap_content” android:drawableStart=”@drawable/google_circle” android:fontFamily=”@font/ubuntu_bold” android:text=”@string/sign_in_with_google” android:textSize=”16sp” tools:ignore=”RtlSymmetry” />
Authenticate with Firebase
- Integrate Google Sign-In into your app by following the steps on the Integrating Google Sign-In into Your Android App page. When you configure the GoogleSignInOptions object, call requestIdToken:
// Configure Google Sign In
//popup all google ac
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
After you integrate Google Sign-In, your sign-in activity has code similar to the following:
//calling that popup window
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
// ...
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
- In your sign-in activity’s onCreate method, get the shared instance of the FirebaseAuth object:
private FirebaseAuth mAuth;
// initialize Firebase auth
mAuth = FirebaseAuth.getInstance();
- When initializing your Activity, check to see if the user is currently signed in:
@Override
protected void onStart() {
super.onStart();
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
- After a user successfully signs in, get an ID token from the GoogleSignInAccount object, exchange it for a Firebase credential, and authenticate with Firebase using the Firebase credential:
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.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
FirebaseUser user = mAuth.getCurrentUser();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(SignIn.this, "Authentication Failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
Get the current user
- Now create a new page for get the current user
- Design the page for the current user
- Here we will display the used image in a Circle Image View, for that we are using a Circle Image View library
- Add the dependency
dependencies {
…………………………
implementation 'de.hdodenhof:circleimageview:3.0.1'}
- Now add these line of codes
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".ProfileActivity"
android:background="@color/white">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/white"
android:theme="@style/AppTheme.NoActionBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<Button
android:id="@+id/logout_button"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="@string/logout"
android:fontFamily="@font/ubuntu_bold"
android:textSize="22sp"
android:textColor="#000000"
android:background="@drawable/done_ripple"
android:layout_marginBottom="80dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<ScrollView
app:layout_constraintTop_toBottomOf="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- Cover Photo-->
<ImageView
android:id="@+id/coverIv"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@color/textPrimary"
android:scaleType="fitXY"
android:contentDescription="@string/app_name">
</ImageView>
<LinearLayout
android:id="@+id/lione"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="100dp"
android:gravity="center_horizontal">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="180dp"
android:layout_height="180dp"
android:id="@+id/profileImage"
android:padding="5dp"
android:src="@drawable/ppp"
app:civ_border_width="2dp"
app:civ_border_color="#000000"/>
</LinearLayout>
<LinearLayout
android:id="@+id/litwo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/lione"
android:layout_marginTop="0dp"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:fontFamily="@font/ubuntu_bold"
android:gravity="center"
android:textColor="#000000"
android:textSize="25sp" />
<TextView
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:fontFamily="@font/ubuntu_bold"
android:gravity="center"
android:textColor="#000000"
android:textSize="20sp" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
Here, user image, name, and Gmail id will display
- For retrieve the user image, we will use the Picasso library for that
Add dependency for that
dependencies { ……………………
implementation 'com.squareup.picasso:picasso:2.71828'
}
- Now use the getLastSignedInAccount method to store the data of the last signed-in user.
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (signInAccount != null){
name.setText(signInAccount.getDisplayName());
email.setText(signInAccount.getEmail());
Picasso.get().load(signInAccount.getPhotoUrl()).placeholder(R.drawable.ppp).into(profileImage);
}
- To sign out a user, call signOut:
logOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getApplicationContext(), SignIn.class);
startActivity(intent);
}
});
Code for Google Sign-In
activity_sign_in_google.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".SignIn"
android:background="@color/white">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/profileImage"
android:layout_width="200dp"
android:layout_height="200dp"
android:padding="5dp"
android:src="@drawable/quiz_logo_primary"
app:civ_border_color="@color/white"
app:civ_border_width="2dp"
app:layout_constraintBottom_toTopOf="@+id/google_signIn_btn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/ubuntu_medium"
android:padding="10dp"
android:text="Welcome to the App"
android:textColor="@color/textPrimaryDark"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/profileImage" />
<Button
android:id="@+id/google_signIn_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="88dp"
android:layout_marginRight="40dp"
android:background="@drawable/google_ripple"
android:drawableStart="@drawable/google_circle"
android:drawablePadding="10dp"
android:fontFamily="@font/ubuntu_bold"
android:paddingStart="30dp"
android:text="@string/sign_in_with_google"
android:textAlignment="textStart"
android:textColor="@color/black"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/textView"
android:elevation="5dp"
tools:ignore="RtlSymmetry" />
<Button
android:id="@+id/skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:fontFamily="@font/ubuntu_bold"
android:onClick="skip"
android:text="@string/skip"
android:textSize="16sp"
android:textColor="@color/textPrimaryDark"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/google_signIn_btn"
android:layout_marginTop="20dp"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_gravity="center"
android:gravity="center"
android:layout_marginBottom="10dp"
app:layout_constraintTop_toBottomOf="@id/skip">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:fontFamily="@font/ubuntu_medium"
android:textColor="@color/background"
android:layout_gravity="center"
android:gravity="center"
android:textAlignment="center"
android:includeFontPadding="false"
android:text="@string/by_using_our_app_you_agree_our"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:layout_marginTop="4dp">
<TextView
android:id="@+id/terms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:fontFamily="@font/ubuntu_medium"
android:textColor="@color/textPrimaryDark"
android:layout_gravity="center"
android:gravity="center"
android:textAlignment="center"
android:includeFontPadding="false"
android:text="@string/terms_and_conditions"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:fontFamily="@font/ubuntu_medium"
android:textColor="@color/background"
android:layout_gravity="center"
android:gravity="center"
android:textAlignment="center"
android:includeFontPadding="false"
android:text="@string/and"
android:layout_marginStart="4dp"/>
<TextView
android:id="@+id/privacy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:fontFamily="@font/ubuntu_medium"
android:textColor="@color/textPrimaryDark"
android:layout_gravity="center"
android:gravity="center"
android:textAlignment="center"
android:includeFontPadding="false"
android:text="@string/privacy_policy"
android:layout_marginStart="4dp"/>
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
GoogleSignInActivity.java
package com.example.quizapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
public class SignIn extends AppCompatActivity {
private GoogleSignInClient mGoogleSignInClient;
private final static int RC_SIGN_IN = 123;
private FirebaseAuth mAuth;
@Override
protected void onStart() {
super.onStart();
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
createRequest();
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.google_signIn_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
}
private void createRequest() {
// Configure Google Sign In
//popup all google ac
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
//calling that popup window
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
// ...
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.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
FirebaseUser user = mAuth.getCurrentUser();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(SignIn.this, "Authentication Failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
public void skip(View view) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
}
activity_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".ProfileActivity"
android:background="@color/white">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/white"
android:theme="@style/AppTheme.NoActionBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<Button
android:id="@+id/logout_button"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="@string/logout"
android:fontFamily="@font/ubuntu_bold"
android:textSize="22sp"
android:textColor="#000000"
android:background="@drawable/done_ripple"
android:layout_marginBottom="80dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<ScrollView
app:layout_constraintTop_toBottomOf="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- Cover Photo-->
<ImageView
android:id="@+id/coverIv"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@color/textPrimary"
android:scaleType="fitXY"
android:contentDescription="@string/app_name">
</ImageView>
<LinearLayout
android:id="@+id/lione"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="100dp"
android:gravity="center_horizontal">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="180dp"
android:layout_height="180dp"
android:id="@+id/profileImage"
android:padding="5dp"
android:src="@drawable/ppp"
app:civ_border_width="2dp"
app:civ_border_color="#000000"/>
</LinearLayout>
<LinearLayout
android:id="@+id/litwo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/lione"
android:layout_marginTop="0dp"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:fontFamily="@font/ubuntu_bold"
android:gravity="center"
android:textColor="#000000"
android:textSize="25sp" />
<TextView
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:fontFamily="@font/ubuntu_bold"
android:gravity="center"
android:textColor="#000000"
android:textSize="20sp" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
ProfileActivity.java
package com.example.quizapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.firebase.auth.FirebaseAuth;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class ProfileActivity extends AppCompatActivity {
TextView name, email;
CircleImageView profileImage;
Button logOut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("PROFILE");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
logOut = findViewById(R.id.logout_button);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
profileImage = findViewById(R.id.profileImage);
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (signInAccount != null){
name.setText(signInAccount.getDisplayName());
email.setText(signInAccount.getEmail());
Picasso.get().load(signInAccount.getPhotoUrl()).placeholder(R.drawable.ppp).into(profileImage);
}
logOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getApplicationContext(), SignIn.class);
startActivity(intent);
}
});
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home){
ProfileActivity.this.finish();
}
return super.onOptionsItemSelected(item);
}
}
For more visit my GitHub account:
or mail me at barmangolap15@gmail.com