Summary: Learn how to enhance your QuickBlox React app with seamless social authentication using Facebook. This tutorial highlights the benefits of integrating the React UIKit for streamlined development and leveraging social login to simplify user registration and login processes, improving user experience and security. Follow step-by-step instructions to set up your Facebook Developer account, create a React application, and implement Facebook authentication effortlessly.
In the world of web development, securing user data is vital. One of the key elements of web application security is user authentication. The use of social authentication providers such as Facebook, Google, Twitter, and others is becoming increasingly popular among developers. This approach not only simplifies the registration and login process for users but also improves application security by using proven authentication mechanisms from major companies.
In this article, we will look at the process of adding authentication using social authentication providers to web applications in React. We will discuss the main advantages of this approach and get acquainted with a tool that greatly simplifies this process – Quickblox React UIKit.
Authentication through social providers, such as Facebook, is a mechanism that allows users to log into web applications using their accounts on these platforms. The login process via Facebook typically involves the following steps:
Authentication through Facebook simplifies the login process for users of your web application, allowing them to use their existing Facebook account without the need to create a new one. This approach can also enhance application security by providing access to verified authentication mechanisms from a major platform.
QuickBlox UIKit for React is a library of user interface (UI) components with implemented business logic, specifically designed to simplify the development process of chat web applications in React. This library provides developers with a wide range of ready-made components that can be easily integrated into their projects, significantly speeding up the process of creating the user interface and improving its quality.
Key features and components of QuickBlox UIKit for React:
Using the UI components provided by QuickBlox UIKit for React has several advantages for developers:
Ready to get started?
Now we have explained the benefits of social authentication and the benefits of the React UIKit, let’s take you through the steps for adding authentication to your application.
To add authentication via Facebook provider to our web application, we will utilize a demo application already using QuickBlox UIKit for React. This will allow us to quickly integrate authentication functionality into an existing project.
First, we will download the sample code from the QuickBlox UIKit for React repository, available at the following link: QuickBlox React UIKit Demo App.
After downloading the sample code, we will install all the necessary libraries using the command in the terminal:
npm install
This will allow you to download all dependencies, including QuickBlox UIKit for React and other libraries required for the application to function.
For this example to work successfully, you need to add credentials to the file src\QBconfig.ts. In this file, you should specify access parameters for QuickBlox, such as appId, accountKey, authKey, authSecret, and sessionToken.
credentials: { appId: -1, accountKey: '', authKey: '', authSecret: '', sessionToken: '', },
To obtain these parameters, you need to register an account on the Quickblox portal at the following link: QuickBlox Registration. Then, within your account, create an application and obtain the credentials. For more detailed information on how to do this, you can refer to our article at the following link: How to create a React application with QuickBlox UIKit.
After making changes to the src\QBconfig.ts file, you can run your application using the command in the terminal:
npm run start
Before we can add authentication via the Facebook provider to our web application, we need to obtain API keys from Facebook. These keys will allow our application to interact with the Facebook API for user authentication and retrieving necessary information about them.
To obtain API keys from Facebook, follow these steps:
Specify the application type as “Authenticate and request data from users with Facebook Login”.
Name your application and select the platform “Web”.
Configure the application: After creating the application, go to the settings page.
Here you will need to specify the domain of your web application, to which Facebook will redirect users after successful authentication. Also, you will need to specify the redirect URI for login, which will be used during authentication through Facebook.
Get API Keys: After configuring the application, you will be able to find the API keys in the application settings section. Facebook will provide you with client and secret keys, which you will need to use in your web application for authentication through Facebook.
After obtaining the API keys from Facebook, we will be ready to proceed with integrating authentication via the Facebook provider into our web application using QuickBlox UIKit for React.
To successfully integrate authentication via the Facebook provider into our web application using QuickBlox UIKit for React, we need to set the corresponding parameters in the administrative panel of our QuickBlox application. In this section, we will go through the steps to add parameters in the QuickBlox admin panel.
After completing these steps, QuickBlox will be ready to use the Facebook API keys for user authentication in your web application. Now we can proceed to integrate authentication via the Facebook provider into our web application using QuickBlox UIKit for React.
First, you need to connect the Facebook SDK to your application. This can be done by adding the SDK to the index.html file of your application or by dynamically loading the SDK in a React component.
In the public/index.html file, add the following code before the closing body tag:
<script> window.fbAsyncInit = function() { FB.init({ appId: 'YOUR_Facebook_APP_ID',// CHANGE YOUR_Facebook_APP_ID to ID your FB app autoLogAppEvents : true, xfbml : true, version : 'v10.0' }); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script>
In the src\QBHelpers.tsx file, add the FB.login method call to perform authentication via Facebook:
export const createUserSessionWithFB = async (): Promise=> { return new Promise((resolve, reject) => { window.FB.login((response: any) => { if (response.authResponse) { const accessToken = response.authResponse.accessToken; QB.createSession({ provider: "facebook", keys:{ token: accessToken, secret: null } }, async (errorCreateSession: any, session: any) => { if (errorCreateSession) { reject(errorCreateSession) } else { const userId: number = session.user_id; const password: string = session.token; const paramsConnect: ParamsConnect = { userId, password }; resolve(paramsConnect); } }); } else { reject("Error! User canceled login or did not fully authorize."); } }, {scope: 'email'}); }); };
In the App component, add methods to perform authentication operations via Facebook:
const loginFBHandler = async (): Promise=> { if (isOnline) { setErrorMessage(''); await loginFBAction(); } else { setErrorMessage('Error! No connection.') } }; const loginFBAction = async (): Promise => { if (isSDKInitialized && !isUserAuthorized) { await createUserSessionWithFB() .then( async resultUserSession => { await connectToChatServer( resultUserSession, currentUser.login) .then( async authData => { await qbUIKitContext.authorize(authData); qbUIKitContext.setSubscribeOnSessionExpiredListener(() => { console.timeLog('call OnSessionExpiredListener ... start') logoutUIKitHandler(); console.log('OnSessionExpiredListener ... end'); }); setSDKInitialized(true); setUserAuthorized(true); document.documentElement.setAttribute('data-theme', theme); navigate('/'); }) .catch( errorChatConnection => { handleError(errorChatConnection); }); }) .catch( errorUserSession => { handleError(errorUserSession); }); } };
In the SignIn component, add a button for authentication via Facebook and a handler for the click event on this button:
<Button size='small' fullWidth variant="contained" sx={{mt: 3, mb: 2}} onClick={signInFBHandler} disabled={!isOnline} > Login with Facebook </Button>
In the src/App.tsx file, pass the loginFBHandler method to all calls of the SignIn component:
<SignIn signInHandler={loginHandler} signInFBHandler={loginFBHandler} errorMessage={errorMessage} isOnline={isOnline} />
After completing all the steps, your web application using Quickblox React UIKit will be ready to perform authentication via Facebook. Let’s run our application and see the result.
Well done! If you successfully followed the steps you should have now added
authentication via Facebook to your web application using QuickBlox UIKit for React.
From a security perspective, we did briefly discuss the option of using a custom proxy server to interact with the Facebook API. This approach allows hiding sensitive data, such as the Facebook application secret key, from end users, and adds additional layers of access control and authentication. However, we will leave a detailed discussion of this topic for a future article on our blog.
We hope that this article has been helpful to you and will assist you in successfully implementing authentication in your projects. Stay tuned to our blog for updates on security and other aspects of web application development.
If you have questions, ideas or just want support consider joining our Discord Developer community!