How To Implement Facebook Auto-login On A Website

0
385

To implement Facebook auto-login on your website, you need to use Facebook Login with the JavaScript SDK. This allows users to log in automatically if they are already logged into Facebook.

Steps to Implement Facebook Auto-login:

1. Create a Facebook App

  1. Go to Facebook Developers.
  2. Click "My Apps" > "Create App".
  3. Select "Consumer" as the app type.
  4. Configure your app, including App Name and App Domain.
  5. Get your App ID from the App Dashboard.

2. Load the Facebook JavaScript SDK

Add the following script inside the <body> tag of your HTML file:

<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId      : 'YOUR_APP_ID',  // Replace with your Facebook App ID
      cookie     : true,
      xfbml      : true,
      version    : 'v18.0'  // Use the latest Facebook Graph API version
    });

    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  };

  (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'));

  function statusChangeCallback(response) {
    if (response.status === 'connected') {
      // User is logged in and has authenticated your app
      fetchUserInfo();
    } else {
      // Not logged in, show login button
      document.getElementById('fb-login-btn').style.display = 'block';
    }
  }

  function fetchUserInfo() {
    FB.api('/me', {fields: 'id, name, email'}, function(response) {
      console.log('User Info:', response);
      document.getElementById('user-info').innerHTML = 
        'Welcome, ' + response.name + '! (' + response.email + ')';
    });
  }

  function loginWithFacebook() {
    FB.login(function(response) {
      if (response.authResponse) {
        fetchUserInfo();
      }
    }, {scope: 'email'});
  }
</script>

3. Add a Facebook Login Button

<button id="fb-login-btn" onclick="loginWithFacebook()" style="display:none;">
  Login with Facebook
</button>
<div id="user-info"></div>

How Auto-login Works

  • When the page loads, FB.getLoginStatus() checks if the user is already logged into Facebook.
  • If logged in, the user information is retrieved automatically.
  • If not logged in, the login button is displayed.

Additional Notes

  • Ensure your App Domain and Redirect URI are correctly set in the Facebook Developer Console.
  • You may need to configure OAuth settings under App Settings > Facebook Login.
  • Use HTTPS for security, as Facebook Login requires secure connections.

Would you like a backend implementation with token validation as well?