How to implement facebook login in android
Authentication using Facebook in Android Studio | Engineering Education (EngEd) Program
Authentication is essential for securing access to specific online content. A user has to provide proof of their identity.
In this article, we will discuss how to implement Facebook authentication in Android apps.
Prerequisites
To follow along, the reader should have:
- Android Studio installed.
- Some basic knowledge of
Kotlin
. - Some knowledge of authentication using
Firebase
.
Goal
At the end of this article, the reader will have learned how Facebook authentication works.
Introduction
When accessing third-party services, most applications require users to identify themselves. One of the popular authentication frameworks is Facebook.
This software giant has an SDK that enables authentication. Therefore, developers can use to ensure that individuals sign in before accessing third-party services.
Firebase overview
Firebase is also a common system for authentication and data storage. It allows users to authenticate themselves using emails
, passwords
, and even phone numbers
.
The firebaseAuth.createUserWithEmailAndPassword(email,password)
method authenticates a person using the provided credetials (email and password).
However, Firebase authentication is tedious and challenging to implement. This is why some developers still build their authentication systems from scratch.
Why Facebook login?
Facebook authentication is superior to other traditional frameworks as follows:
-
When individuals sign in using Facebook, they grant your app permission to access information or perform different actions.
-
With a Facebook login, the user does not need to create a new account to access your app’s content.
In this tutorial, we will create an application that authenticates users using Facebook.
The application will also display the user’s Facebook details. For instance username, email, birthday, gender, and profile pic
.
Step 1: Getting started
In this step, we will create a project with an empty activity
template.
In Android Studio, navigate to the top left corner and click on File -> New -> New Project -> Empty Activity.
Step 2: Connecting your application to Firebase
At the top of your Android Studio
, click on Tools
then on Firebase
. On the assistant window that appears on your right select Authentication
.
You need to select Facebook
and connect to Firebase
. The next step is to add Firebase Authentication
to your app.
On your browser open the Firebase console
and then select your project. Under authentication
, click on Facebook
and enable it.
Step 3: Facebook for developers
Navigate to https://developers. facebook.com/ and create an account (If you do not have one).
Then click on my apps
to create a new app. On the drop-down menu, select Consumer
then click next
. Enter the app details
to complete the registration.
On your left, click on Settings
and select basic
. You can now copy the App ID
and App Secret
.
Paste these details into the Firebase console fields
under Facebook authentication
.
Now, click on the dashboard
and choose the Facebook setup
option. Select Android
and click on next.
Step 4: Adding dependencies
In your settings.gradle
file, add mavenCentral()
under repositories.
In the app level build.gradle
file, include the following dependencies:
//Glide implementation 'com.github.bumptech.glide:glide:4. 12.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0' //Facebook implementation 'com.facebook.android:facebook-android-sdk:12.1.0'
Also, add the following setting in the build.gradle
file:
buildFeatures { viewBinding true }
Step 5: Generating the Hash Key
Using your SHA1
key, generate a hash key
and paste it in the key hashes option
.
Step 6: Editing the Manifest and String files
Add the following lines of code to your Manifest.xml
and string.xml
files:
Manifest.xml
<uses-permission android:name="android.permission.INTERNET"/> //in Application <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/> <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>
String.xml
<string name="facebook_app_id">214268554165523</string> <string name="fb_login_protocol_scheme">fb214268554165523</string>
Step 8: Creating the user interface
Our user interface will include the following components:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas. android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:id="@+id/profile_pic" android:layout_width="150dp" android:layout_height="150dp" android:layout_marginTop="32dp" android:scaleType="centerCrop" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" android:src="@drawable/com_facebook_favicon_blue"/> <TextView android:id="@+id/user_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:textColor="@color/black" android:padding="10dp" android:text="Name" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/profile_pic" /> <TextView android:id="@+id/user_gender" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:textColor="@color/black" android:padding="10dp" android:text="Gender" app:layout_constraintEnd_toEndOf="@+id/user_name" app:layout_constraintStart_toStartOf="@+id/user_name" app:layout_constraintTop_toBottomOf="@+id/user_name" /> <TextView android:id="@+id/user_b_day" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:padding="10dp" android:textColor="@color/black" android:text="Birthday" app:layout_constraintEnd_toEndOf="@+id/user_gender" app:layout_constraintStart_toStartOf="@+id/user_gender" app:layout_constraintTop_toBottomOf="@+id/user_gender" /> <TextView android:id="@+id/user_email" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:padding="10dp" android:textColor="@color/black" android:text="Email" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="@+id/user_b_day" app:layout_constraintTop_toBottomOf="@+id/user_b_day" /> <View android:id="@+id/view" android:layout_width="150dp" android:layout_height="2dp" android:layout_marginTop="32dp" android:background="@color/black" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/user_email" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:text="Sign in with:" android:textColor="@color/black" android:textSize="16sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="@+id/view" app:layout_constraintStart_toEndOf="@+id/view" app:layout_constraintTop_toTopOf="@+id/view" /> <View android:id="@+id/view2" android:layout_width="150dp" android:layout_height="2dp" android:layout_marginStart="8dp" android:background="@color/black" app:layout_constraintBottom_toBottomOf="@+id/view" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@+id/textView5" app:layout_constraintTop_toTopOf="@+id/view" /> <com. facebook.login.widget.LoginButton android:id="@+id/login_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="24dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView5" /> </androidx.constraintlayout.widget.ConstraintLayout>
Note that we have imported <com.facebook.login.widget.LoginButton/>
from the Facebook authentication package.
Step 9: MainActivity
We need to include some logic in the MainActivity.kt
file. Note that I have explained the following code using in-line comments.
import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import com.facebook.* import com.facebook.login.LoginResult import com.thecalvary.facebooklogindemo. databinding.ActivityMainBinding import org.json.JSONObject import java.util.* private const val TAG = "MainActivity" class MainActivity : AppCompatActivity() { //To avoid findViewById, we use view binding. private lateinit var binding: ActivityMainBinding //Declare the Facebook callbackmanager private lateinit var callBackManager: CallbackManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view: View = binding.root setContentView(view) //Now initialize the callbackmanager callBackManager = CallbackManager.Factory.create() //set the login button with permissions to read and add to a list all user data binding.loginButton.setReadPermissions(listOf("email","public_profile","user_gender","user_birthday")) //A callback is registered when the login button is clicked. //The callback can return an error or success message. It can also be canceled binding.loginButton.registerCallback(callBackManager, object : FacebookCallback<LoginResult>{ override fun onCancel() { // this method is invoked when the request is cancelled Toast.makeText(this@MainActivity, "Cancelled", Toast.LENGTH_SHORT).show() } override fun onError(error: FacebookException) { Toast.makeText(this@MainActivity, "$error", Toast.LENGTH_SHORT).show() } //Incase of an error, the above message is displayed. override fun onSuccess(result: LoginResult) { val graphRequest = GraphRequest.newMeRequest(result?.accessToken){`object` ,response -> getFacebookData(`object`) } val parameters = Bundle() parameters.putString("fields", "id,email,birthday,gender,name") graphRequest.parameters = parameters graphRequest. executeAsync() } }) } //This function gets the users' Facebook data. //This includes the username, email, birthday, gender, and profile picture. //As they appear on Facebook private fun getFacebookData(jsonObject: JSONObject?) { val profilePic = "https://graph.facebook.com/${jsonObject ?.getString("id")}/picture?width=500&height=500" Glide.with(this) .load(profilePic) .into(binding.profilePic) val name = jsonObject?.getString("name") val birthday = jsonObject?.getString("birthday") val gender = jsonObject?.getString("gender") val email = jsonObject?.getString("email") binding.userName.text = "Name: ${name}" binding.userEmail.text = "Email: ${email}" binding.userBDay.text = "Birthday: ${birthday}" binding.userGender.text = "Gender: ${gender}" } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) callBackManager. onActivityResult(requestCode, resultCode, data) } }
When you run the above application, you should be able to access Facebook authentication.
Conclusion
In this tutorial, we have discussed some basic aspects of Facebook Authentication. You can, therefore, use this knowledge to craft other beautiful applications.
Further reading
- Facebook for developers
- Firebase
Peer Review Contributions by: Wanja Mike
The right way to implement Facebook login for your app | by Taylor Hughes
Taylor Hughes is a co-founder at Cluster, which builds web and mobile apps that enable users to create private sharing environments for groups, travelers, classrooms, and more.
Logging in with Facebook theoretically solves a lot of problems for app developers. But it’s not overly clear the best way to go about it, and many examples on the web advocate the wrong strategy.
Here’s what we’ve learned integrating Login with Facebook in Cluster.
Use your own long-lived session tokens
Facebook sessions get invalidated all the time. The Facebook SDK can provide your app with an invalid session token due to cached data at the SDK or system level; auth tokens expire due to user behavior like resetting passwords or manually invalidating apps under the user’s settings.
So, after signup, your app should not assume you can ever get another valid token from the Facebook SDK. In some cases, if you want to keep the session alive, you might have to prompt the user to authenticate with Facebook again.
To avoid a critical mistake I made, here’s the most important thing: Don’t ever block your app’s startup on third-party authentication.
Instead, you should implement your own session token strategy, and it should probably be made to resemble OAuth3. Rather than extending sessions by passing the original credentials to the backend, you should ask your backend for a new token using a separate refresh token.
As a result, authentication flows with Facebook, Google, et al, should look something like this:
- User hits “Login with Facebook”
- Facebook SDK talks to Facebook backend to get a token
- Your client gives your backend the token
- Your backend validates the token against Facebook’s servers
- Your backend issues a new authentication or session token
- Your client saves your backend’s auth token: Now you’re logged in and can talk to your own servers forever, or at least in a way you understand.
Next we can talk about how to keep the Facebook session alive in the client as long as possible.
Persisting Facebook “connectedness” across logins and devices
Once a user signs in with Facebook, she might sign in with another service under the same email address. Or a different user might “Connect” his account to Facebook later, which should associate his Facebook session with his user account in the backend.
But when these guys sign in on another device, or if they sign out and sign back in (without tapping “Login with Facebook”), the Facebook SDK in the client might not know about their Facebook sessions anymore.
Additionally, the only way to keep sessions alive is to refresh them in the client; there’s no facility for doing this on the server.
So, to wire the session back up, when a user who has logged in with Facebook (or connected his or her Facebook account) logs back in, your app should do the following:
- Load any recent third-party sign-in tokens from your backend
- Re-create the Facebook/Google login sessions and issue a request
- Check the auth token. If it has changed, save the new token to your backend to keep the session alive.
You can replicate this behavior on Android and the web so that when a user signs into a different client, you can silently keep them connected.
Code for re-inflating Facebook sessions on iOS
Many Bothans died to bring us this information. It’s very difficult to find documentation around this.
So here’s a brief snippet of code from our iOS client that shows how this is done.
Good luck!
Thanks for reading this! Any thoughts? If you enjoyed this article, I would really appreciate you hitting the recommend button below. Connect with me on Twitter @taylorhughes with any comments or thoughts.
Configuring the application for integration with Facebook (up to and including version 10.0)
Integration of your accounts in Webim and Facebook is registered as an application of the network * Facebook *. This article explains how to create and configure such an application.
Check that your page meets all the necessary requirements
- Log in to Facebook using the link, enter the login and password of that particular account ( account) Facebook , on behalf of which the page was created (or will be created) and the integration will be registered. It is recommended to use the account that owns the page. If she has a different role on the desired page, Facebook will not provide access to it for integration.
!!! Note "NB" Access for integration is granted only to page administrators. Also note that losing access to this account will result in the integration being unable to be managed. Therefore, it may be useful to create for these targets a separate account. nine0009
-
If Page of your project has not yet been created, create it now. For this you can use our instruction.
-
Make sure your project has Privacy Policy and preferably * End User Agreement/Terms * posted on separate web pages. Otherwise, write them now. nine0009
-
Make sure that your project has a logo or other unique image that characterizes it, and that you have intellectual rights to it and a file with a bitmap display of the logo. Otherwise, take care of the logo now (logo size - 1024 x 1024 pixels).
-
Make sure that the Facebook account has valid data that you can confirm in case checks (name, surname, date of birth, e-mail address, phone number, photo, etc. ), and also at the ready a passport or other document (for example, a driver's license) confirming the identity of this account. AT otherwise, supplement or correct these data. Further Facebook may ask you for Additional information.
Facebook registration for Developers
- Go to the home page of the Facebook for Developers service using this link. The developer page will open. The same account Facebook is used here as usual, but for those who starts working with the service for the first time, you need to additionally register your account. Click here Get started .
Facebook for Developers homepage
- This will open the welcome window. Click here Continue :
Welcome window Facebook for developers
- At this stage Facebook performs the first check. If, when registering your account or its editing, you did not specify your phone number, an additional form may appear where you will be asked to indicate your phone number and verify it. If the additional form does not appear, go to the next step of this instructions. nine0020
Create application
- After the welcome window, a page appears with a button Create app . Click it.
Page with Create Application button
- In the application type selection window, select Business .
Selecting the type of Webim
application- Then you need to enter Display name of the application (Display name) and Contact email address of the application ( App Contact Email) . If necessary, please verify that you are not a robot (captcha).
Creating a Webim
applicationApplication preset
- Next, the product setup page will open, displaying several sections for configuring the product. In chapter * Messenger push button Set Up *.
Setting up the Webim
application- You will be taken to the Messenger settings for the app. Section Access Tokens click Add or remove pages (Add or remove pages) . Select the page where you want to set up the integration (page Your company) and press Next and then Done .
Adding page
- In section Access tokens the page you added and the button Generate Token will appear, by clicking on it, a window for confirming the generation of the marker will open. In this window you will see a warning that in for security purposes, the generated access token will only be shown once. Immediately copy the marker and paste it into a previously opened blank text document to eliminate the possibility of loss. nine0020
Generated access token
Application setup on this can be considered complete. Information about integration with Facebook can be found in this article.
-
The activities of the Meta corporation, as well as its Facebook and Instagram platforms, are recognized as extremist and banned in the Russian Federation. ↩
What is Off-Facebook Activity and how to set it up
You probably know that Facebook collects data about you. Moreover, the company receives information for your dossier not only from your page on the social network, but also from many sites and applications that, at first glance, have nothing to do with Facebook at all. And if you decide whether to post something on Facebook or not, then third-party services, as a rule, do not even tell you to whom and what data they transfer. nine0009
Off-Facebook Activities
Not so long ago, an important tool appeared in the Facebook settings that allows you to view and manage information that the company received from third parties. It's called Actions Off Facebook. To find it:
- Click on the triangle (web version) or menu icon (mobile app) in the upper right corner of the screen.
- Select Settings and privacy .
- Open Settings .
- Go to section Your Facebook information .
- Click Off-Facebook activities .
Of course, it is not possible to simply stop data collection. But by digging into the "Acts outside of Facebook", you can find out who and what says about you social networks, and untie unnecessary information from your profile, and this is already a lot.
Who tells Facebook what you're doing
Sites and apps that use a variety of social media tools, from the "Log in with Facebook" button to analytics tools, can share information with Facebook. nine0009
Right on the page Off-Facebook activities you can see the last few "speakers". To see the full list, click Manage your off-Facebook activity information , then you'll need to enter your password.
Most likely, the scale of data collection will impress you: among Facebook partners there may be news portals, and banking applications, and resources that you don’t remember at all, because, for example, you accidentally visited them only once, hitting them from a search . nine0009
What data sites and applications transmit to Facebook
“Off-Facebook activities” is primarily information about your interaction with third-party services. For example, a media site can tell the social network that you have read the latest news, and an online store that you have viewed or bought a particular product. And this section can also include the actions of the site or application itself, for example, displaying ads.
In the Facebook settings, it only shows the number of actions shared by this or that resource, but you can download the archive with the details. For this:
- Go to Settings -> Your information on Facebook -> Off-Facebook activity -> Manage information about off-Facebook activity .
- On the page with a list of applications that send information about your activities to Facebook, click Downloading your information . In the mobile application, you will first have to click on the icon in the upper right corner of the screen.
- If necessary, select what data and for what period to download: by default, Facebook will create an archive with all information related to you, including your posts, social network activities, and so on. If you are only interested in the data reported by third-party services, uncheck all boxes except Advertising and companies .
- Click Create file .
Depending on what data you want to download, it will take from several minutes to several days to create an archive. If you're only interested in information about off-Facebook activity, it's likely to be prepared quickly. As soon as the archive is available, you will receive a social media notification and an email.
Facebook notes that it actually receives more data from third-party services than it shows you. Nevertheless, information from the archive may be interesting. In addition, if you find, say, too sensitive data in the list of actions, you can complain about the service that transmitted it to Facebook. For this:
- Go back to Settings -> Your information on Facebook -> Off-Facebook activity -> Manage information about off-Facebook activity .
- In the list of sites and applications, click on the name of the service.
- Click Provide feedback on these activities .
- Select the reason for the complaint.
How to remove data already collected from your Facebook account
Facebook allows you to remove data collected about you from your profile. To do this, go to Go to Settings -> Your information on Facebook -> Offline activities and click Clear history above the list of sites and applications - and your previous online activity will not affect what ads the social network shows you.
How to prevent sites from transmitting data to Facebook
It is impossible to completely stop communication between Facebook and third-party services: sites and applications will in any case tell the social network some information about you. Sometimes individual resources get caught transmitting too personal data and change their approach, but this has nothing to do with Facebook settings. nine0009
On the other hand, the social network may not link information about actions in third-party services to your profile and may not use it to display personalized advertising. This can be configured for individual sites and applications, or for all at once.
To stop Facebook adding specific property data to your account:
- Go to Settings -> Your information on Facebook -> Off-Facebook activities -> Manage information about off-Facebook activities .
- Click on the name of the resource in the list and in the window that opens, select Disable sending future actions for [site name] .
- Press button Disable .
After that, within two days, Facebook will stop giving you ads based on information from this resource. True, there is a downside to the coin: you will not be able to use the “Login with Facebook” button on it until you allow it to be linked to the profile again. nine0009
You can also completely turn off the sending of data by sites and applications. But get ready for the consequences: after that, you will be immediately thrown out of all the services where you entered using the social network. If there are many of them, it can be very inconvenient.
To completely prevent Facebook from targeting ads based on the sites and apps you use:
- On the Manage Off-Facebook Activity Information page for a list of services that have shared information about you with Facebook, press Managing future actions . In the web version, this item is on the screen on the right, and in the mobile application it is hidden in the menu behind three dots.
- Press Manage future actions .
- Disable option Future actions outside of Facebook .
- Press Disable .
Done! Now the social network will no longer bombard you with shoe ads if you recently bought a pair of sneakers.