Integrate Facebook and Google Authentication using Firebase full tutorial for beginners with 2018 new Code


Hello everyone here I am with an other Firebase tutorial in this tutorial we will add Facebook and Google authentication using Firebase and also we will create an awesome looking UI for this project to log in... So lets start coding...

The post make this kind of interface watch this video-


First thing first if you are a beginner then don't worry just follow all the codes step by step don't miss any one or if you know something about this then just jump to the main code...

First we will create an Android project so Open Android studio and create a new project...

Here I am using a project with minimum SDK of 21 and Targeted version is 28 so this is most resent and new..

So after you create the project then we need to create a firebase project in which we will store our user data and more... So to create firebase project I will recommend you to follow the link bellow this is my old post to create firebase project and add firebase messaging feature to android application the creation of firebase project is nothing change so follow this link-



Click here- 

👇

2018 tutorial with updated dependency "Firebase Cloud Messaging and Firebase In-App Messaging "

So after you create the project in firebase come back to the android project. So first lets create some layout for batter work so lets create the UI.

So go o the Link bellow and copy all the images and drwable files to your project after that open app module gradle file and paste this dependency this dependency help us to add the google sign in button widget to our XML file...

Now add the bellow code to your activity_main.xml file...



Now open app module gradle file and paste another dependency...

OK now Open your MainActivity.java and paste the code this will just add the login via google but the Facebook will not work we have to make more changes...



Now you can run the application and see the Google authentication is working 😃

After your checking is completed come back to project now we need to add Facebook authentication to the project but this is not that easy you need to follow all the steps one by one otherwise you can not add it may be you add the code but when you run the app did not allow you to sign in using Facebook so follow all the steps...

Step 1

Open Facebook for Developed and create a application there.


Step 2

Click on settings and then click basic then copy App ID and App Secret


Step 3

Open Firebase console and open authentication and then paste the App ID and Secrets and also copy OAuth redirect URI


Step 4



Now in Facebook developer click facebook login and open settings and scroll down a little bit and paste the OAuth redirect URI here.


Step 5

Now open Facebook Developer Setting Page and fill this like a form...

Step 5.1.

Chose your application from the drop down.


Step 5.2

Now add this codes in your project level build file and app level build file


Step 5.3

Now add this codes in your manifest file and string file read the doc in the Facebook developer page


Step 5.4

Now add your android package name and the activity name where you want to add sign in in my case pakage name is com.monstertechno.test and the activity is com.monstertechno.test.MainActivity after adding it click save.


Step 5.5

This is the step where everyone stuck but I have a solution to do that if we use this way the we can not stuck here... Just paste this key aia+XHL1UpXfH6tkX650PLzteDY= here and save this we will edit it when we complete all coding.



Step 5.6

Click on single Sign on and this work is finished we can process for coding..


Step 6

Open your MainActivity.java and just configure some of the codes and we done..

Step 6.1

First add this two variable in your project

private CallbackManager mCallbackManager; 
private Button facebook;

Step 6.2

Now add this codes in your onCreate methode

//FacebookLogIn
mCallbackManager = CallbackManager.Factory.create();

facebook = (Button) findViewById(R.id.facebookLogin);

Step 6.3

Now add this code in your onCreate method.

facebook.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        mCallbackManager = CallbackManager.Factory.create();
        LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("email", "public_profile"));
        LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.d(TAG, "facebook:onSuccess:" + loginResult);
                handleFacebookAccessToken(loginResult.getAccessToken());            }

            @Override
            public void onCancel() {
                Log.d(TAG, "facebook:onCancel");                
// ...            }

            @Override
            public void onError(FacebookException error) {
                Log.d(TAG, "facebook:onError", error);
                // ...            }
        });    }
});

Step 6.4

Now copy this code and paste this under the onActivityResult function..

// 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, update UI appropriately        // ...    }
}else{
    mCallbackManager.onActivityResult(requestCode, resultCode, data);
}



Step 6.5

Now paste this code outside the onCreate method..

private void handleFacebookAccessToken(AccessToken token) {
    Log.d(TAG, "handleFacebookAccessToken:" + token);
    progressDialog = ProgressDialog.show(this, "Loading...", "Please wait Posts is Loading...");
    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    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,br/>                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        progressDialog.dismiss();
                        mAuth.addAuthStateListener(mAuthListener);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(LoginActivity.this, "Authentication failed. Please Use another Account.",                                Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }

                    // ...                }
            });}

Now run the application and when you trying to sign in with facebook it shows an error like that-


that the hash key dose not match so copy the hash key from that error and paste the key in developer page and then try to run the application again and now it work perfectly.

NOTE: Hash key are sensitive when you are using debug application then it generate one key when you signed your app then it generates another hash key and when you upload the signed apk to play store it generates another hash key so make sure you save all the three hash key in developer page other wise it gives you error.

Thanks for your time make sure you follow other posts and share this posts with your friends...

Comments

  1. "So go o the Link bellow and copy all the images and drwable files to your project"
    link is not attached , please share it

    ReplyDelete
  2. the hash key that i get in the error not working
    what to do plss tell

    ReplyDelete

Post a Comment