Facebook Account Kit & Single-SignOn (SSO)
- Digital Engineering
Facebook Account Kit & Single-SignOn (SSO)
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:
- Create the UI which includes two buttons – Login By SMS, Login by Email
- 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> - Initialize Account Kit and setup JS handlers for login callback.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
<?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> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
$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; } ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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
Auriga: Leveling Up for Enterprise Growth!
Auriga’s journey began in 2010 crafting products for India’s