Skip to content

Facebook Authentication via Firebase

namnh-0652 edited this page Apr 3, 2023 · 9 revisions

Features

Installation

Prerequisites

Create Facebook Application & Link to Firebase project

  • Go to Facebook developer site and create your application.
    • Save your App Id.
    • Go to Setting > Basic > save your App secret.
    • Go to Setting > Advanced > save your Client token.
  • Go to Dashboard > Add products to your app, select Facebook Login.
  • Go to Firebase project > Authentication > Enable Facebook in Sign-in method.
    • Add App Id.
    • Add App secret.
    • Copy OAuth redirect URI and go to Facebook app
    • Paste URI to Facebook Login > Settings > Valid OAuth Redirect URIs.
  • Go to Facebook Login > QuickStart > Add settings for your Android application.

Notes: For additional settings please read Facebook documents for detail. Depending on the Facebook data you request from people using Facebook Login , you may need to submit your app for review prior to launch.

Add library

From project build.gradle (or settings.gradle), add Jitpack maven

repositories {
    maven { url 'https://jitpack.io' }
}

Add these dependencies to your app/build.gradle

dependencies {
    implementation "com.github.sun-asterisk.tech-standard-android-auth:core:${latest_version}"
    implementation "com.github.sun-asterisk.tech-standard-android-auth:facebookfirebaseauth:${latest_version}"
}

Usage

SignIn Facebook with Firebase Authentication

Setup your FacebookConfig

From Application class, call initFacebookFirebaseAuth method

initFacebookFirebaseAuth(
     appId = getString(R.string.facebook_app_id),
     clientToken = getString(R.string.facebook_client_token),
) {
     readPermissions = listOf("email", "public_profile")
     enableAppEvent = false
     enableLoginStatus = true
}

Add Facebook activity to your Manifest

<activity android:name="com.facebook.FacebookActivity"
    android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" />

<activity android:name="com.facebook.CustomTabActivity"
    android:exported="true">    <!--To support Web login-->
    <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" /> <!--fbAPP-ID Ex: fb111000111000111--> 
    </intent-filter>
</activity>

Initialize Activity/Fragment with callbacks you want to get authentication result

From your FragmentActivity or Fragment.

fun initFacebookSignIn(activity: FragmentActivity) {
    FacebookFirebaseAuth.initialize(
         activity,
         signInCallback = object : SignInCallback<AuthResult> {
             override fun onResult(data: AuthResult?, error: Throwable?) {
                  _signInState.value = SocialAuthResult(data = data, error = error)
             }
         }
    )
}

Important Note:

  • Because this client is designed follow LifecycleObserver, so call initialize method before Activity or Fragment falls in STARTED state.

Finally, call signIn Facebook

fun signIn() {
    FacebookFirebaseAuth.signIn()
}

SignIn via Facebook LoginButton

Sets LoginButton permissions

// via FacebookConfig
initFacebookFirebaseAuth(...) {
    useFacebookLoginButton = true // required
    readPermissions = listOf("email", "public_profile")
}
// or directly
binding.facebookSignIn.permissions = listOf("email", "public_profile")

Sets LoginButton

FacebookFirebaseAuth.setLoginButton(binding.facebookSignIn)

Note: SignIn via Facebook LoginButton, you do not need to call SignIn() method.

Sequence diagram

sequenceDiagram
    autonumber
    participant Application
    participant FacebookFirebaseAuth
    note over FacebookFirebaseAuth: FacebookFirebaseAuth Module
    participant Facebook
    Application->>FacebookFirebaseAuth: check SignIn status
    FacebookFirebaseAuth->>Firebase: check SignIn status
    Firebase-->>FacebookFirebaseAuth: response status
    alt is Signed In
        rect rgb(0, 0, 255, .1)
            break when is SignedIn
                FacebookFirebaseAuth-->>Application: 
            end
        end
    else is Not Signed In
        FacebookFirebaseAuth-->>Application: 
    end
    Application->>FacebookFirebaseAuth: send SignIn() request
    FacebookFirebaseAuth->>Facebook: request SignIn
    Facebook->>Facebook: Handle Request
    alt signIn process fails
        rect rgb(0, 0, 255, .1)
            break
                Facebook-->>FacebookFirebaseAuth: return error
                FacebookFirebaseAuth-->>Application: Callback error
            end
        end
    else signIn Success
        Facebook-->>FacebookFirebaseAuth: return AccessToken
    end
    FacebookFirebaseAuth->>Firebase: signIn Firebase with Credentials
    Firebase->>Firebase: Handle Request
    alt signIn process fails
        rect rgb(0, 0, 255, .1)
            break
                Firebase-->>FacebookFirebaseAuth: return error
                FacebookFirebaseAuth-->>Application: Callback error
            end
        end
    else signIn Success
        Firebase-->>FacebookFirebaseAuth: return AuthResult
        FacebookFirebaseAuth-->>Application: Callback AuthResult
    end
Loading

Check signed in status

fun isSignedIn(): Boolean {
    return FacebookFirebaseAuth.isSignedIn()
}

Gets signed in FirebaseUser

fun getUser(): FirebaseUser? {
    return FacebookFirebaseAuth.getFirebaseUser()
}

Gets Facebook Token or Profile

fun getFacebookToken(): AccessToken? {
    return FacebookFirebaseAuth.getAccessToken()
}

fun getFacebookProfile(): Profile? {
    return FacebookFirebaseAuth.getProfile()
}

SignOut current user

fun signOut() {
    FacebookFirebaseAuth.signOut(object : SignOutCallback {
        override fun onResult(error: Throwable?) {
            _signOutState.value = error
        }
    })
}

Gets Firebase Multiple Auth Providers UserInfo

You can allow users to sign in to your app using multiple authentication providers by linking auth provider credentials to an existing user account. Users are identifiable by the same Firebase user ID regardless of the authentication provider they used to sign in. For example, a user who signed in with a password can link a Google account and sign in with either method in the future. Or, an anonymous user can link a Facebook account and then, later, sign in with Facebook to continue using your app.

To get the UserInfo of linked account

fun getUserInfo(): UserInfo? {
    return FacebookFirebaseAuth.getLinkedAccounts(PROVIDER_FACEBOOK)
}

Documentation

Method/field Purpose
appId: String Facebook application id
clientToken: String Facebook client token
readPermissions: List List of read permissions
enableLoginStatus: Boolean Enable to check login status, default true
enableAppEvent: Boolean Sets auto logging events flag, default true
useFacebookLoginButton: Boolean Sets flag use Facebook LoginButton, default false
Method Purpose
fun signIn(): Unit Start SignIn process
fun setLoginButton(button: LoginButton): Unit Sets Facebook LoginButton
fun isSignedIn(): Boolean Check current SignIn status
fun signOut(): Unit SignOut current User
fun getFirebaseUser(): FirebaseUser? Gets current Firebase user
fun getProfile(): Profile? Gets current Facebook Profile
fun getAccessToken(): AccessToken? Gets current Facebook AccessToken
fun getLinkedAccounts(provider: String): UserInfo? Gets Firebase Multiple Auth Providers UserInfo