Skip to main content

Android Sign In Using Google | Firebase Auth | No Server Required | Free

In this tutorial I will show you how to setup google sign in to your application without server side code using firebase.

Firebase is an amazing tool it enables many features such as Analytics, Admob, Database, Hosting, Authentication, Dynamic links ,Authentication etc. The major goal of Firebase is that it do not need any server side codes.

Complete Video Tutorial

Download Code : Download

Step 1:Get your SHA Fingerprint

In order to add google sign in feature you have to submit your SHA fingerprint of your application to google. If you run or build your application for at least one time you can generate SHA by Clicking

Gradle >{Your App Name } > :app > android > Signing Report

Gsignin

Double click on signing Report to generate SHA Fingerprint. Copy the SHA Fingerprint for the next step

Step 2:Login to Firebase

You can easily login to firebase using your google account at free of cost. Create a New Project and add a New Android Application on the firebase console.

gsignin

Paste the copied SHA to firebase (*For google SignIn it is Mandatory)

Step 3 :Add Google-Services.json to your project

Save the downloadable JSON File (google-services.json) Copy the file and paste it directly to app folder

gson

Step 4:Add Dependencies and Plug-ins

Add the following dependencies and plug-ins to your code. Add the following lines to your module level build.gradle file

dependencies

{

// your project dependencies

compile 'com.google.android.gms:play-services-auth:9.4.0'
compile 'com.google.firebase:firebase-auth:9.4.0'
compile 'com.google.firebase:firebase-messaging:9.4.0'
compile 'com.google.firebase:firebase-core:9.4.0'
compile 'com.google.firebase:firebase-crash:9.4.0'

}



apply plugin: 'com.google.gms.google-services'

sync the project to download the required dependencies.

If any error occurs make sure you are connected to Internet and your Project level build.gradle having the dependency

//add this line
        classpath 'com.google.gms:google-services:3.0.0'

 

Step 5 :Sign In check on Main Activity

Define the following variables

// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
public static final String ANONYMOUS = "anonymous";

private String mUsername;
private String mPhotoUrl;

add the following inside onCreate()

//  add these just after setContentView(R.layout.activity_main);
// Initialize Firebase Auth
    mUsername = ANONYMOUS;
    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseUser = mFirebaseAuth.getCurrentUser();
    if (mFirebaseUser == null) {
        // Not signed in, launch the Sign In activity
        startActivity(new Intent(this, SignInActivity.class));
        finish();
        return;
    } else {
        mUsername = mFirebaseUser.getDisplayName();
        if (mFirebaseUser.getPhotoUrl() != null) {
            mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
        }
        Log.i("User Name:",mUsername;
    }
}

Optimize the Imports

Step 6 : Create Sign In Activity

Copy the following java file and name it SignInActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
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 SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,
        View.OnClickListener {

    private static final String TAG = "SignInActivity";
    private static final int RC_SIGN_IN = 9001;
    private SignInButton mSignInButton;

    private GoogleApiClient mGoogleApiClient;
    private FirebaseAuth mFirebaseAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);

        // Assign fields
        mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);

        // Set click listeners
        mSignInButton.setOnClickListener(this);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        // Initialize FirebaseAuth
        mFirebaseAuth = FirebaseAuth.getInstance();
    }

    private void handleFirebaseAuthResult(AuthResult authResult) {
        if (authResult != null) {
            // Welcome the user
            FirebaseUser user = authResult.getUser();
            Toast.makeText(this, "Welcome " + user.getEmail(), Toast.LENGTH_SHORT).show();

            // Go back to the main activity
            startActivity(new Intent(this, MainActivity.class));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                signIn();
                break;
            default:
                return;
        }
    }

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        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) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                // Google Sign In failed
                Log.e(TAG, "Google Sign In failed.");
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mFirebaseAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());

                        // If sign in fails, display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "signInWithCredential", task.getException());
                            Toast.makeText(SignInActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            startActivity(new Intent(SignInActivity.this, MainActivity.class));
                            finish();
                        }
                    }
                });
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        // An unresolvable error has occurred and Google APIs (including Sign-In) will not
        // be available.
        Log.d(TAG, "onConnectionFailed:" + connectionResult);
        Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
    }

}

Make a layout File for the sign in activity

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:id="@+id/sign_in_layout"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:gravity="center"
             android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="40dp"
        android:text="sign_in"/>

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="visible"
        android:layout_gravity="center"/>

</FrameLayout>

Define SignInActivity On your Manifest.xml By adding the following

 

 

<activity android:name=".SignInActivity" />

Step 7: Run the Project

SignInScreen

You can check the login details on Firebase console

console

  • pjoshi235

    Get error in MainActivity.java
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    Need ‘;’

    • sooraj shankar

      Hello @pjoshi235:disqus

      Can you send me the logcat report , The downloadable project works for me fine.
      and i didn’t used onConnectionFailed at MainActivity.java
      Please try importing the project for reference .

      Regards,
      sooraj

  • re assa

    tried your tutorial. im getting Google Sign In Failed. how to fix?

    • admin

      Hello ,
      Thank you for your question but this Question is not enough !

      Please insert the stack trace.

  • srushtee satardey

    please tell me how to go to another activity after signing in

  • João Vitor

    to many errors for me.. i dont noo why..

  • Saurabh Singh Rajput

    nyc article this is really helping
    technoedit.com