Android Firebase Authentication (Facebook authentication) take-home memo

Introduction

This is a memo of Android Firebase Authentication (Facebook authentication). It's definitely for me, but I hope it helps. The IDE is Android Studio.

References

google login authentication method http://qiita.com/Sert/items/1fbdbf68dd087201a57b google, Facebook, Twitter, email & password authentication method http://qiita.com/ronnnnn/items/dddf57a0369f780d8ac2

I referred to this. Also, it seems that there was no article dedicated to Facebook, so I will write it down.

Sign up for Facebook for developers

account registration

This is omitted.

Android application registration you want to authenticate

SnapCrab_NoName_2017-7-2_22-30-45_No-00.png

Press Add New App.

SnapCrab_NoName_2017-7-2_22-33-18_No-00.png

Then, enter an appropriate name in the display name. Then a security check will appear, so we will break through it. Then the screen will change, so press Facebook login and then the next Android.

SnapCrab_NoName_2017-7-2_22-37-49_No-00.png

Did you get a screen like this? Let's do this. For Android Studio

  1. Skip the Facebook SDK for Android. Please press Next.

  2. Import the Facebook SDK. build.gradle (project)

build.gradle(project)


buildscript {
    repositories {
        jcenter()
        mavenCentral()//Add here
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
    }
}
allprojects {
    repositories {
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle (app)

build.gradle(app)


...

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'//Add here
}

This is the end.

  1. Enter the Android project information. This describes the package name and the Acitivity class name. This time, for the package name, add package = "..." in manifest.xml. Since we want to set LoginActivity → MainActivity, the default is LoginActivity, so write package name.LoginActivity.

next Save → use this package name Please click. This is the end of 3.

  1. Add development key hash and release key hash Since this time it is a private premise, only the development key hash is generated.

I'm Windows

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64

Click to paste. By the way, I use Windows bash, so I can use the keytool command. It was not possible at the command prompt. Windows Bash is convenient, so let's install it.

Windows Bash installation http://qiita.com/Aruneko/items/c79810b0b015bebf30bb And to make a clean terminal https://www.sa-sa-ki.jp/blog/2016/12/bash-on-ubuntu-on-windows-wsl-terminal/ It would be nice to use a tool like this: sunny:

Paste the command result with. Save → Next

  1. Enable single sign-on for your app I will skip it.

  2. Add Facebook App ID Follow the description.

  3. Add FacebookActivity to AndroidManifest.xml This is also as described.

  4. Enable Chrome Custom Tabs This is also as described

It looks like this.

Manifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="jp.app.oomae.hisaki.facebook">

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Well, there is still more.

Register with Firebase

Next, register the application in Firebase and declare that you will use Facebook. Add Project → Project name (arbitrary name) → Add project → Add Firebase to Android app

SnapCrab_NoName_2017-7-2_23-16-50_No-00.png

Because it looks like this Android package name: Similar to the one entered in Facebook for developers earlier

App nickname: omitted

Signature certificate for debugging SHA-1 (optional): this is

keytool -exportcert -list -v \
-alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore

Paste this into Windows Bash. Then press Enter and enter the password "android"

SnapCrab_NoName_2017-7-2_23-23-52_No-00.png

Since it is output like this, SHA1: hogehogelldpksvopd

Hogehogelldpksvopd Paste only this part and register the application. Next, put google-services.json in the PATH as described. Next, play with build.gradle as described.

build.gradle(project)



buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.1.0'//add to
    }
}
allprojects {
    repositories {
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(app)


...

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
}
apply plugin: 'com.google.gms.google-services'//add to

SnapCrab_NoName_2017-7-2_23-35-15_No-00.png

Next is the Authentication settings.

Try using (Authentication) → Login method → Facebook At this point, you will be asked for the application ID and secret ID. Open Facebook for developers again and check the dashboard.

SnapCrab_NoName_2017-7-2_23-37-24_No-00.png

This. : muscle:

Then go to Firebase again, enter it and copy the OAuth redirect URI.

Also, open Facebook for developers and

SnapCrab_NoName_2017-7-2_23-44-43_No-00.png

Press Facebook Login on the left and paste the URL you just copied into a valid OAuth redirect URI. Then press Save Changes at the bottom right.

Go to Firebase again and save. This completes the Firebase side as well.

Implementation

Using the above, we will create an application such as Login → Transition → Logout → Transition → ... with LoginActivity when authenticating with Firebase.

First, play with build.gradle (app)

build.gradle


compile 'com.google.firebase:firebase-core:11.0.1'
compile 'com.google.firebase:firebase-auth:11.0.1'

Next, make sure that LoginActivity is called first in Manifest.xml.

Manifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="jp.app.oomae.hisaki.facebook_authentication_sample">

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity">
        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
        </activity>
        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Next, create an Activity. The transition source LoginActivity.java and the transition destination MainActivity.java.

LoginActivity.java


package ;

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.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
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.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;

public class LoginActivity extends AppCompatActivity {

    private FirebaseAuth firebaseAuth;
    private CallbackManager callbackManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // get firebase instance
        firebaseAuth = FirebaseAuth.getInstance();
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_login);

        // initialize facebook login button
        callbackManager = CallbackManager.Factory.create();
        FacebookCallback<LoginResult> facebookLoginCallback = new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                firebaseAuthWithFacebook(loginResult.getAccessToken());
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onError(FacebookException error) {
                if (error != null) {
                    DialogManager.createDialog(LoginActivity.this, error).show();
                }
            }
        };
        LoginButton facebookLoginButton = (LoginButton) findViewById(R.id.login_button);
        facebookLoginButton.setReadPermissions("email", "public_profile");
        facebookLoginButton.registerCallback(callbackManager, facebookLoginCallback);
    }

    private void firebaseAuthWithFacebook(AccessToken token) {
        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        firebaseAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            changeActivity();
                        } else {
                            Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void changeActivity() {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
    }
    //FaceBook
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
}

MainActivity.java



package ;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.facebook.login.LoginManager;

public class MainActivity extends AppCompatActivity {

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

        findViewById(R.id.logoutButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LoginManager.getInstance().logOut();
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
}

Create a file to manage the dialog.

DialogManager.java


package ;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;

public class DialogManager {
    static AlertDialog createDialog(Context context, String message) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
        alertDialog.setMessage(message);
        alertDialog.setPositiveButton("dialog close", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int id) {
                dialogInterface.dismiss();
            }
        });
        return alertDialog.create();
    }

    static AlertDialog createDialog(Context context, Throwable throwable) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
        alertDialog.setMessage(throwable.getMessage());
        alertDialog.setPositiveButton("dialog close", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int id) {
                dialogInterface.dismiss();
            }
        });
        return alertDialog.create();
    }
}

Next is the layout file.

activity_login.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp" />

</LinearLayout>

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="15dp"
    android:paddingLeft="15dp"
    android:paddingRight="15dp"
    android:paddingTop="15dp"
    tools:context=".LoginActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login success!"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="48dp"
        android:textSize="32dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Logout"
        android:id="@+id/logoutButton"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:textSize="26dp" />
</RelativeLayout>

This is the end. Thank you for watching till the end! !! We welcome your questions and comments. : point_up:

GitHub:https://github.com/hisakioomae/Firebase_Authentication_Facebook_Sample

Recommended Posts

Android Firebase Authentication (Facebook authentication) take-home memo
Firebase Authentication Note