Facebook Authentication with Firebase
Last Updated :
15 Apr, 2025
User authentication is a fundamental aspect of app development, ensuring secure access to user data and personalization. Firebase, a platform by Google, offers seamless integration with various authentication providers, including Facebook.
In this guide, we will explore how to implement Facebook Authentication with Firebase, complete with examples and outputs.
Understanding Facebook Authentication
- Facebook Authentication allows users to sign in to our app using their Facebook credentials.
- It provides a convenient and familiar way for users to access your app without the need to create new accounts or remember additional passwords.
Setting Up Firebase Project
Before diving into implementation, you'll need to set up a Firebase project and integrate it into your app:
- Create a Firebase Project: Go to the Firebase Console (console.firebase.google.com) create a new project and follow the setup instructions.
- Add Firebase to Your App: For web or mobile apps, add Firebase to your project by including the Firebase SDK. Firebase provides platform-specific SDKs and setup instructions for various platforms.
Implementing Facebook Authentication
1. Adding Facebook Authentication to Your App
For a web app we will include Firebase and Facebook SDKs in our HTML file:
<!-- Firebase App (the core Firebase SDK) -->
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js"></script>
<!-- Firebase Auth (specifically for authentication) -->
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-auth.js"></script>
<!-- Facebook SDK -->
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>
Explanation:
- The first two script tags include the Firebase SDK for the core functionality (firebase-app.js) and authentication (firebase-auth.js), which are essential for integrating Firebase services, including authentication, into the web application.
- The third script tag includes the Facebook SDK which is used for integrating Facebook login functionality into the application for authentication purposes.
2. Initialize Firebase and Set Up Facebook Authentication
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
appId: "YOUR_APP_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize Facebook SDK
window.fbAsyncInit = function() {
FB.init({
appId: 'YOUR_FACEBOOK_APP_ID',
cookie: true,
xfbml: true,
version: 'v13.0'
});
// Check Facebook Login status
FB.getLoginStatus(function(response) {
// Handle the response
});
};
Explanation: The code snippet initializes Firebase and the Facebook SDK in a web application.
firebaseConfig
contains the configuration information required to initialize Firebase, including the API key, authentication domain, project ID, and app ID.
firebase
.
initializeApp
(
firebaseConfig
)
initializes Firebase using the provided configuration.
window
.
fbAsyncInit
is a callback function that initializes the Facebook SDK. It sets up the Facebook app ID, enables cookies, initializes the Facebook Markup Language (XFBML), and specifies the version of the Facebook Graph API to use.
FB
.
getLoginStatus
checks the current login status of the user with Facebook. The response object contains information about the user's login status, which can be used to handle the response accordingly
3. Implementing Facebook Sign-In
function signInWithFacebook() {
FB.login(function(response) {
if (response.authResponse) {
const credential = firebase.auth.FacebookAuthProvider.credential(
response.authResponse.accessToken
);
// Sign in with the Facebook credential
firebase.auth().signInWithCredential(credential)
.then((userCredential) => {
// Signed in successfully
const user = userCredential.user;
console.log(user);
})
.catch((error) => {
console.error(error.message);
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
Explanation: This signInWithFacebook
function handles the sign-in process using Facebook authentication in a web application. Here's a breakdown of how it works:
FB.login
is a Facebook SDK method that prompts the user to log in to their Facebook account and authorize the app.
- The
response
parameter in the callback function of FB.login
contains the user's response to the login prompt.
- If the user successfully logs in and authorizes the app (
response.authResponse
is truthy), the function creates a Firebase credential using the Facebook access token (response.authResponse.accessToken
).
- The
firebase.auth().signInWithCredential(credential)
method signs the user in to Firebase using the Facebook credential.
- If the sign-in is successful, the
then
block is executed, and the user's information is logged to the console.
- If the user cancels the login or does not fully authorize the app, the
else
block is executed, and a message is logged to the console.
4. Handling User Authentication State
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in
console.log("User is signed in");
} else {
// No user is signed in
console.log("No user is signed in");
}
});
Explanation: This code sets up a listener for authentication state changes in Firebase. When the authentication state changes (i.e., a user signs in or signs out), the provided callback function is called with the current user object.
- If a user is signed in (
if (user)
), it logs "User is signed in" to the console.
- If no user is signed in (
else
), it logs "No user is signed in" to the console.
This listener is useful for updating the UI based on the user's authentication state, such as showing different content or navigation options for authenticated and unauthenticated users.
Example: Facebook Authentication in Action
Let's consider a simple web application where users can sign in using their Facebook accounts.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Firebase Auth with Facebook</title>
</head>
<body>
<h1>Sign In with Facebook</h1>
<button onclick="signInWithFacebook()">Sign In with Facebook</button>
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-auth.js"></script>
<script>
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
appId: "YOUR_APP_ID"
};
firebase.initializeApp(firebaseConfig);
function signInWithFacebook() {
FB.login(function(response) {
if (response.authResponse) {
const credential = firebase.auth.FacebookAuthProvider.credential(
response.authResponse.accessToken
);
firebase.auth().signInWithCredential(credential)
.then((userCredential) => {
const user = userCredential.user;
console.log(user);
})
.catch((error) => {
console.error(error.message);
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
</script>
</body>
</html>
Explanation: This HTML file sets up a basic web page for signing in with Facebook using Firebase Authentication. It includes a button that triggers the signInWithFacebook
function, which uses the Facebook SDK to handle the login process. Upon successful login, the function creates a Firebase credential with the Facebook access token and signs in to Firebase. The user object is then logged to the console
Conclusion
Facebook Authentication with Firebase provides a convenient and secure way for users to sign in to your app using their Facebook accounts. By following the steps outlined in this guide, you can integrate Facebook Authentication seamlessly into your web or mobile app.
Firebase Authentication offers additional features like user management, custom claims, and integrations with other Firebase services, making it a comprehensive solution for user authentication needs. Start implementing Facebook Authentication with Firebase today and enhance the user experience of your applications!
Similar Reads
Google Authentication with Firebase
Google Authentication, a method of verifying user identities using Google credentials, provides a seamless and secure way for users to sign in to applications. With the help of Firebase, developers can integrate Google Authentication into their apps and allowing users to sign in with their existing
5 min read
Django Authentication Project with Firebase
Django is a Python-based web framework that allows you to quickly create efficient web applications.. When we are building any website, we will need a set of components: how to handle user authentication (signing up, signing in, signing out), a management panel for managing our website, how to uploa
7 min read
GitHub Authentication with Firebase
GitHub Authentication in Firebase allows users to sign in to our web application using their GitHub credentials. This integration uses GitHub's OAuth authentication system which provides a secure and convenient way for users to access your app. By integrating GitHub authentication, we can enhance us
5 min read
Twitter Authentication with Firebase
Twitter Authentication allows users to sign in to applications using their Twitter credentials, providing a simple and familiar sign-in experience. By integrating Twitter Authentication with Firebase, developers can simplify the authentication process and enhance the user experience. In this article
5 min read
Firebase Phone Authentication
Phone Authentication in Firebase is a secure method of verifying user identities using their phone numbers. It simplifies the sign-in process by sending verification codes via SMS and ensuring that only users with access to the phone number can sign in. In this article, We will learn to set up and i
5 min read
What is Firebase Authentication
Firebase Authentication is a powerful backend service offered by Google Firebase, designed to speed up the user authentication process in applications. Supporting various authentication methods, such as email/password, phone number, and social logins, Firebase Authentication ensures secure user auth
4 min read
How to Use Authentication Console in Firebase?
Almost all apps need to have some permission system in place. In some circumstances, checking a username/password pair against our Users table is sufficient. Still, frequently, we require a more detailed permissions model to grant specific users access to particular resources while preventing them f
4 min read
Types of Authentications in Firebase
Firebase is a Backend-as-a-Service (Baas) provided by Google which helps developers to build, manage, and grow their apps easily. It provides multiple tools and services to the developers to build quality and secure applications. It is built on Google's Infrastructure. It provides services to multip
4 min read
How to Add a Custom Domain in Firebase Authentication?
Firebase Authentication provides users with one of the most secure ways of logging in to their applications meant for the web or app. Firebase is a platform developed by Google which offers a wide range of tools and services to help developers build high-quality apps and websites. In this article, W
3 min read
Firebase Custom Authentication Using Cloud Functions
Firebase Custom Authentication offers a flexible solution for generating custom tokens with our own authentication logic. These tokens can be used to authenticate users in your Firebase project and making it ideal for integrating existing user systems, third-party authentication providers or custom
4 min read