Home/Facebook Account Kit & Single-SignOn (SSO)

Facebook Account Kit & Single-SignOn (SSO)

Published On: 22 November 2016.By .
  • Product & platform Engineering

Passwordless login provides a hassle-free signup and login experience for the user. The user does not have to remember passwords, rather they are provided a one-time password or link delivered via SMS or email, which verifies the user. Companies like Medium, Slack, and Twitter have already adopted this system.

Single Sign On (SSO) enables user to log in to n number of services using a single account. A blend of Passwordless login and SSO can greatly amplify the security and adoptability of such system.

Introduction to Facebook Account Kit

Facebook has rolled out Facebook Account Kit to provide passwordless authentication. Users authenticating through it is not necessarily a registered Facebook user.

Currently users can log in simply by providing their email address or phone number. Facebook Account Kit send an one-time passcode or link to the respective mobile number or email address and verifies using them. It also offers certain customisations like colors of links, headings, buttons in the dialog box.

Integrating Facebook Account Kit for Passwordless Login

Today we will learn how to integrate Facebook Account Kit into our applications. Facebook has released SDKs for Android, iOS and Javascript. We will use Javascript SDK in our application where PHP will server as backend.

STEP 1: Get Started

To get started, you should to have a Facebook Developer Account and a Facebook App. You can use an existing app or create a new one and enable Account Kit for the App. To enable Account Kit, navigate to the Account Kit tab in the Facebook app and do as directed. To process the requests, the backend needs your App ID which can be located on the dashboard of your Facebook app and your Account Kit App Secret which is found in the Account Kit tab.

Having the credentials in order, let’s see the implementation at the backend.

Steps to follow:

  1. Create the UI which includes two buttons – Login By SMS, Login by Email
  2. Import the Account Kit Javascript SDK by adding this line in the <head> tag:
    <script src=”https://sdk.accountkit.com/en_US/sdk.js”></script>
  3. Initialize Account Kit and setup JS handlers for login callback.
<?php
session_start();
?>
<html>
<head>
  <title>Fb test</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.indigo-pink.min.css">
  <script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>
  <script
        src="http://code.jquery.com/jquery-1.12.4.min.js"
        integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
        crossorigin="anonymous"></script>
  <script src="https://sdk.accountkit.com/en_US/sdk.js"></script>
  <style>
    body {
      text-align: center;
      background: #EEE;
    }
    .mdl-switch {width:auto;}
    .btnfull {width: 100%;}
  </style>
</head>
<body>
  <div class="mdl-grid">
    <div class="mdl-cell mdl-cell--4-col mdl-cell--4-offset">
      <div class="mdl-card mdl-shadow--2dp">
      <div class="mdl-card__supporting-text">
          <h1 class="mdl-typography--title">Facebook Account Kit Demo</h1>
      <?php
      if(isset($_SESSION['username'])):
      ?>
      <p>Hello <?=$_SESSION['username']?>. You're logged In.</p>
      <p><a href="response.php?logout=true">Logout</a>
      <?php
      else:
      ?>
      <div id="block_login">
        <form method="post" action="response.php" id="frm_login">          
          <input type="hidden" name="login"/>
          <input type="hidden" name="code" id="login_code"/>
          <input type="hidden" name="login_via" id="login_via"/>
        </form>


        <ul class="demo-list-icon mdl-list">
          <li class="mdl-list__item">
            <button onclick="loginWithSMS();" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored mdl-typography--text-center btnfull">Login By SMS</button>
          </li>
          <li class="mdl-list__item">
                <button onclick="loginWithEmail();" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent mdl-typography--text-center btnfull">Login By Email</button>
          </li>
        </ul>


      </div>


      <?php endif; ?>


      </div>
      </div>
    </div>
  </div>


  <script>
    // initialize Account Kit with CSRF protection
    AccountKit_OnInteractive = function(){
      AccountKit.init ({
          appId:"you_app_id_here",
          state:"you_Account_kit_client_token_here",
          version:"your_account_kit_api_version",
          debug: true
});
    };


    // login callback
    function loginCallback(response) {
      if (response.status === "PARTIALLY_AUTHENTICATED") {
        document.getElementById("login_code").value = response.code;
        document.getElementById("frm_login").submit();
      }
      else if (response.status === "NOT_AUTHENTICATED") {
        alert("Auth failure");
        return false;
      }
      else if (response.status === "BAD_PARAMS") {
        alert("BAD_PARAMS");
        return false;
      }
    }


    function loginWithSMS(){
      document.getElementById("login_via").value = 1;
      AccountKit.login("PHONE",{}, loginCallback);
    }


    function loginWithEmail(){
      document.getElementById("login_via").value = 2;
      AccountKit.login("EMAIL", {}, loginCallback);
    }


  </script>
<?php
if(isset($_SESSION['message']) && !empty($_SESSION['message'])){
  echo "<script type='text/javascript'>alert('".$_SESSION['message']."');</script>";
  $_SESSION['message'] = '';
}
?>
</body>
</html>

screenshot-from-2016-11-17-17-46-13

screenshot-from-2016-11-18-10-21-07

screenshot-from-2016-11-18-10-20-29

screenshot-from-2016-11-18-10-20-41

screenshot-from-2016-11-22-18-15-11

screenshot-from-2016-11-22-18-17-34

Note: You can also create for to read country code, mobile number or email and pass it to Account Kit.

As you can see, after getting response from Account Kit loginCallback function gathers the data, assign it to the form and submits the form. The data from the form is collected in the file response.php, where Graph API is used to fetch the logged in user details and add it to our database, if required.

$dbname = 'dbname';
$dbuser = 'dbuser';
$dbpwd = 'dbpwd';
$dbhost = 'localhost';


$facebook_app_id = "facebook_app_id";
$app_secret = "app_secret";


$mysqli = new mysqli($dbhost, $dbuser, $dbpwd, $dbname);


if (mysqli_connect_errno()) {
  printf("Connect failed: %s\n", mysqli_connect_error());
  exit();
}


if(isset($_POST['login'])){
  $login_via = $_POST['login_via'];
  $code = $_POST['code'];


  /* Get Account data via Graph */
  $graph_url = "https://graph.accountkit.com/v1.0/access_token?grant_type=authorization_code&code=".$code."&access_token=AA|".$facebook_app_id."|".$app_secret;
  $result = json_decode(file_get_contents($graph_url), true);
  if($result['id']){
    $account_id = $result['id'];
    $account_url = "https://graph.accountkit.com/v1.0/me/?access_token=".$result['access_token'];
    $account_data = json_decode(hitCurl($account_url), true);
    if(isset($account_data['phone'])){
      $country_code = '+'.$account_data['phone']['country_prefix'];
      $mobile = $account_data['phone']['national_number'];
    } elseif(isset($account_data['email'])){
      $email = $account_data['email']['address'];
    }
    if($login_via == 1){
      $q = "SELECT * FROM `users` where country_code='".$country_code."' AND mobile='".$mobile."'";
    } else {
      $q = "SELECT * FROM `users` where email='".$email."'";
    }  
    $rs = $mysqli->query($q);
    $row_count = $rs->num_rows;
    if($row_count)
    {
      $user = $rs->fetch_assoc();
      if($user['name'])
        $_SESSION['username'] = $user['name'];
      elseif($user['mobile'])
            $_SESSION['username'] = $user['mobile'];
      elseif($user['email'])
            $_SESSION['username'] = $user['email'];
    } else {
      $q1 = "INSERT INTO `test`.`users` (`id`, `name`, `country_code`, `mobile`, `email`, `account_id`) VALUES (NULL, '', '".@$country_code."', '".@$mobile."', '".@$email."', '".@$account_id."')";
      $row1 = $mysqli->query($q1);
      if($row1){
        $msg = "You are successfully registered & logged In. Please complete your profile. Id: ".$mysqli->insert_id;
        if($login_via == 1){
              $_SESSION['username'] = $mobile;
        } else {
              $_SESSION['username'] = $email;
        }      
      } else {
            $msg = 'Error : ('. $mysqli->errno .') '. $mysqli->error;
      }
      $_SESSION['message'] = $msg;
    }
  } else {
    $_SESSION['message'] = "Some error. Try Again!";
  }
  /**/


  header('Location: index.php');
  exit(0);
}


function hitCurl($url){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $result = curl_exec($ch);
  curl_close($ch);
  return $result;
}
?>
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `country_code` varchar(5) NOT NULL,
  `mobile` varchar(15) NOT NULL,
  `email` varchar(30) NOT NULL,
  `account_id` varchar(1000) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);


ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Note: When you choose email option, make sure that you do not close the dialog box, Account Kit will automatically close it once the link is clicked. An important point to be mentioned here is that even if one clicks the link on different device it will still work.

Account Kit Login

Login to Account Kit to view the list of websites logged in using that account.

Thanks for reading.

Related content

We Love Conversations

Say Hello
Go to Top