Quantcast
Channel: Blog – Stormpath User Identity API
Viewing all articles
Browse latest Browse all 278

Facebook Login Guide

$
0
0

Facebook Login Guide

Social login is becoming a more and more popular form of web authentication — it’s easy and convenient for users, which means more and more sites are adopting it. When it comes to social login, there are essentially two providers people care about: Facebook and Google.

At Stormpath, we recently built our own Facebook and Google Login integration — and figured we’d share what we’ve learned recently in this article.

This article will show you exactly how Facebook Login works, and how you can easily plug it into your website.

NOTE: If you’re looking for a drop-dead easy way to do Facebook Login, you might want to check out our brand new Facebook Login integration. I think you’ll enjoy it.

High Level Overview

I’m sure you’ve used Facebook Login at least once or twice (if not, where do you live? Under a rock!?).

The way Facebook Login works is theoretically quite simple:

  • A user visits your site and sees a big “Sign in with Facebook” button somewhere.
  • A user clicks that button, and gets a little popup window asking the user to accept an array of permissions.
  • The user clicks “Okay”, the popup closes, and the user is back on their original page — but this time, they’re “logged in”.

This high-level flow is what’s known as OAuth 2.0. OAuth is convenient for users because it means they don’t need to manually create an account on each website they visit — they can use a single account everywhere.

Adding Facebook Login to Your Site

Adding Facebook Login to a site is a fairly involved process. The simplest way to do it is by using the Facebook Javascript SDK.

The idea is that you add a button to your site which, when clicked, redirects the user to Facebook to accept permissions, then back to your site when everything is done.

The downside to using Facebook Login this way is that all authentication is done via Javascript, so complex server-side applications require substantially more work to function.

This guide will cover using the Javascript SDK only (as it is much simpler to explain).

Getting Started: Create a Facebook App

The first thing you need to do in order to support Facebook Login on your site is create a Facebook App.

To do this, you’ll want to head over to the Facebook Developer Center and create or log into your Facebook account.

Once you’ve logged in, you should be redirected back to the main Facebook Developer page, where you’ll see a top navbar that looks like this:

Facebook Dev Center Navbar

To create a new Facebook App, click the “Apps” navbar tab, then click “Create a New App”. You’ll now see a window where you can enter a “Display Name” (usually the name of your website), and pick a “Category” (the category of your website).

You should see something that looks like this:

Facebook Create App

Enter these values, then click “Create App”. This will provision a new Facebook App for your website, eventually allowing users to log into your website.

After you’ve created your new Facebook App, you’ll be redirected to your new App dashboard! If all went well, you should now be at a page that looks like this:

Facebook App Dashboard

This Dashboard page contains some useful stats (how many people have logged into your website?) which you might find useful in the future — as well as your Application’s ID and Secret.

The Application ID and Secret will be used later on.

Set Your Site URL

In order to support Facebook Login, you need to let Facebook know what URL(s) your website will be running at. This way, Facebook can verify that a user is actually being asked for permissions from the correct Facebook App.

To do this, click the “Settings” tab on the left nav menu, and click the “Add Platform” button near the bottom of the page.

When prompted, select “Website” as your platform.

In the “Site URL” box that appears, you’ll want to enter your website URL.

For this example, I’m going to enter “http://localhost:8000” — as I’m going to be testing this out on my local machine, on port 8000. You might want to set this to something like: “http://mysite.com” if you’re testing this out on a public domain.

Facebook URLs

NOTE: If you want to allow Facebook Login to work from multiple URLs (maybe you use http://localhost:8000 for local development, and https://mysite.com in production) you can simply click the “Add Platform” button again and enter another URL.

Include the Facebook Javascript SDK in Your HTML

The next thing you need to do is include the Facebook Login button somewhere on your website. You can do this by copy+pasting the following code into your HTML code (this will render a Facebook Login button on your website).

Here’s the code you need to add:

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
<button onclick="facebookLogin()">Facebook</button>
<script>
  function facebookLogin() {
    var FB = window.FB;
    var scopes = 'email,user_likes,public_profile';

    FB.login(function(response) {
      if (response.status === 'connected') {
        console.log('The user has logged in!');
        FB.api('/me', function(response) {
          console.log('Good to see you, ' + response.name + '.');
        });
      }
    }, {scope: scopes});
  }

  window.fbAsyncInit = function() {
    FB.init({
      appId      : 'YOUR_FACBEOOK_APP_ID',
      cookie     : true,
      xfbml      : true,
      version    : 'v2.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 = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
</script>

There are a few things to take notice of here:

  1. You can choose what permissions you request from the user by modifying the scopes variable (in this example it is set to request 'email,user_likes,public_profile). For more information on Facebook permissions, visit this page: https://developers.facebook.com/docs/facebook-login/permissions

  2. You need to replace YOUR_FACBEOOK_APP_ID with your App ID number from the App Dashboard page you saw earlier.

  3. When a user clicks the Facebook button, the facebookLogin() Javascript function will run. This is what controls the pop-up, and post-login behavior. In this case, after a user has logged in, we’re using the Facebook API to grab the user’s information and print some debug information to the developer console.

If you run this code in a simple HTML document, you’ll get a page that looks like the following:

Facebook Login Raw

When you click the Facebook button, you should then see the standard permissions pop-up — it looks like this:

Facebook Perm Request

Lastly, when you accept the permissions, you’ll notice that our Javascript console.log messages worked!

Facebook Console

Handle User Authentication

After including the Facebook Login button on your site, you can then handle user authentication with Javascript.

On any web page where you want to enforce user authentication, you can do something like the following:

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
<script>
  FB.getLoginStatus(function(response) {
    if (response.status === 'connected') {
      // If the user gets here, they're logged in.
      console.log('Logged in.');
    }
    else {
      // Redirect unauthenticated users to the login page.
      window.location.replace('/login');
    }
  });

  window.fbAsyncInit = function() {
    FB.init({
      appId      : 'YOUR_FACBEOOK_APP_ID',
      cookie     : true,
      xfbml      : true,
      version    : 'v2.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 = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
</script>

The FB.getLoginStatus function provided by the Facebook Javascript SDK allows you to easily check to see whether or not the current visitor is successfully authenticated with Facebook (or not).

This code above will redirect any non-authenticated users back to the login page (/login), and all other users will remain on the page.

NOTE: While this is great for simple apps, if you’re building something where security is an issue, you should probably use the more complicated server-side Facebook authentication flow. Stormpath makes this incredibly easy: https://stormpath.com/blog/the-social-integration/

Conclusion

Facebook Login (via Javascript) isn’t that bad! It’s easy to implement and style (you can change your button styles with CSS), but for more complex authentication requirements, you should probably use the server-side flow.

Hopefully this short guide has been helpful! Have any questions? Shoot us an email! support@stormpath.com


Viewing all articles
Browse latest Browse all 278

Trending Articles