How to add firebase Authentication to your Android Studio

NewImage
Firebase Authentication is a good and secure way to get the indentity of your user.It leverages industry standards like OAuth 2.0 and OpenID Connect.
FirebaseUI as a complete drop-in auth solution. The FirebaseUI Auth component implements best practices for authentication on mobile devices and websites, which can maximize sign-in and sign-up conversion for your app. It also handles edge cases like account recovery and account linking that can be security sensitive and error-prone to handle correctly. You can access the user's basic profile information, and you can control the user's access to data stored in other Firebase products.

Step 1: Create New Project on AndroidStudio. Configure your new project such as Application Name, Company Domain, and Project Location.
NewImage

2. Just accept the default form factors your apps will run on.
NewImage

3. Select add Empty Activity for your Mobile Android app.
NewImage

4. Goto Tools menu, and click the new Firebase. Select the  Authentication and Conect to Firebase. next Click Add firebase Authentication to your apps. It will automatically add the following classpath to the build.gradle (project level) and Add the following code to the app/build.gradle
 
  1. Project-level build.gradle (<project>/build.gradle):
    buildscript { dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:3.0.0' } }
  2. App-level build.gradle (<project>/<app-module>/build.gradle):
    ...
    // Add to the bottom of the file
    apply plugin: 'com.google.gms.google-services'
    includes Firebase Analytics by default

NewImage

5. You will got the following error.
Error:Execution failed for task ':app:processDebugGoogleServices'.
> File google-services.json is missing. The Google Services Plugin cannot function without it.  Don’t worry we will fix the error in the next step.
NewImage

6. Add firebase to your Android app and enter the Package name that we created earlier in step 1.

NewImage

For SHA1, go to terminal and type the following code.

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

For window user, follow the StackOverflow discussion over here.

7. Swith to project mode and drag and drop the google-service.jason to you app folder.

NewImage

8. Go to Firebase console and go the Auth menu and enable Google Sign in Provider.
NewImage

9. Add google sign in button in your main layout activity
<com.google.android.gms.common.SignInButtonandroid:id="@+id/sign_in_button"android:layout_width="wrap_content"android:layout_height="wrap_content" />
 
NewImage
 
10. On you onCreate method configure Google Sign in to request user data by using GoogleSignObject
 
  // Configure sign-in to request the user's ID, email address, and basic// profile. ID and basic profile are included in DEFAULT_SIGN_IN.GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
 
NewImage
 
11. Then also in main_activity onCreate method, create GoogleApiClient object to access Google Sign-In API and the options you specified.
 
 
NewImage
 
Copy the following code.
 
package androidrich.com.firebaseauthtest;
import android.app.ProgressDialog;
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.TextView;
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.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
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 MainActivity extends AppCompatActivity implements        GoogleApiClient.OnConnectionFailedListener,
        View.OnClickListener {

    private static final String TAG = "GoogleActivity";
    private static final int RC_SIGN_IN = 9001;

    // [START declare_auth]    private FirebaseAuth mAuth;
    // [END declare_auth]
    private GoogleApiClient mGoogleApiClient;
    private TextView mStatusTextView;
    private TextView mDetailTextView;
    private ProgressDialog mProgressDialog;

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

        // Views        mStatusTextView = (TextView) findViewById(R.id.status);
        mDetailTextView = (TextView) findViewById(R.id.detail);

        // Button listeners        findViewById(R.id.sign_in_button).setOnClickListener(this);
        findViewById(R.id.sign_out_button).setOnClickListener(this);
        findViewById(R.id.disconnect_button).setOnClickListener(this);

        // [START config_signin]        // Configure Google Sign In        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        // [END config_signin]
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        // [START initialize_auth]        mAuth = FirebaseAuth.getInstance();
        // [END initialize_auth]    }

    @Override    public void onStart() {
        super.onStart();

        // Check for existing sign-in        FirebaseUser user = mAuth.getCurrentUser();
        updateUI(user);
    }

    // [START onactivityresult]    @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);
            // [START_EXCLUDE]            handleGoogleSignInResult(result);
            // [END_EXCLUDE]        }
    }
    // [END onactivityresult]
    // [START auth_with_google]    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
        // [START_EXCLUDE silent]        showProgressDialog();
        // [END_EXCLUDE]
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener() {
                    @Override                    public void onComplete(@NonNull Task 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(MainActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                        // [START_EXCLUDE]                        hideProgressDialog();
                        // [END_EXCLUDE]                    }
                });
    }
    // [END auth_with_google]

    private void handleGoogleSignInResult(GoogleSignInResult result) {
        Log.d(TAG, "handleSignInResult:" + result.getStatus());
        if (result.isSuccess()) {
            // Successful Google sign in, authenticate with Firebase.            GoogleSignInAccount acct = result.getSignInAccount();
            firebaseAuthWithGoogle(acct);


            

        } else {
            // Unsuccessful Google Sign In, show signed-out UI            updateUI(null);
        }
    }

    // [START signin]    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
    // [END signin]
    private void signOut() {
        // Firebase sign out        mAuth.signOut();

        // Google sign out        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback() {
                    @Override                    public void onResult(Status status) {
                        updateUI(null);
                    }
                });
    }

    private void revokeAccess() {
        // Firebase sign out        mAuth.signOut();

        // Google revoke access        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                new ResultCallback() {
                    @Override                    public void onResult(Status status) {
                        updateUI(null);
                    }
                });
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage(getString(R.string.loading));
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.hide();
        }
    }

    private void updateUI(FirebaseUser user) {
        hideProgressDialog();
        if (user != null) {
            mStatusTextView.setText(getString(R.string.google_status_fmt, user.getEmail()));
            mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid()));

            findViewById(R.id.sign_in_button).setVisibility(View.GONE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
        } else {
            mStatusTextView.setText(R.string.signed_out);
            mDetailTextView.setText(null);

            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
        }
    }

    @Override    public void onConnectionFailed(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();
    }

    @Override    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                signIn();
                break;
            case R.id.sign_out_button:
                signOut();
                break;
            case R.id.disconnect_button:
                revokeAccess();
                break;
        }
    }
}




<com.google.android.gms.common.SignInButton
 android:id="@+id/sign_in_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>

<com.google.android.gms.common.SignInButton
 android:id="@+id/sign_in_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>



Watch Official Video from Google
How to add firebase Authentication to your Android Studio How to add firebase Authentication to your Android Studio Reviewed by Admin on 5:44 AM Rating: 5

4 comments:

  1. doesnt works, i dont have a "default_web_id"

    ReplyDelete
  2. One super successful app Google launched is Voice Actions, which allows users to write messages and make calls by voice. It has continued to grow bigger and better over the years. Download ShowBox APK

    ReplyDelete
  3. Information technology is the usage of computers to keep, retrieve, transmit, and manipulate facts or facts.
    Random Email Generator
    Black light app
    Temp mail
    Terrarium TV App

    ReplyDelete

Powered by Blogger.