QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Login Using Facebook Tutorial

Login Using Facebook Tutorial

facebook-login

In this post we will look at building a Facebook login system without using Facebook SDK. This mechanism can be followed by any website to integrate Facebook login into it. In this post we will be using a very high level abstraction to build a completely working and secure Facebook login system which will work on web apps.

We have used php for building our login system but you can use any other language as the procedure is same.


View Demo


What is OAuth?

OAuth is a protocol used to allow secure authorization to websites and applications. There are two versions of OAuth, 1.0 and 2.0. In this post we will use OAuth 2.0 to build a Facebook login system.


What is Facebook Log In?

“Facebook Login In” means asking user to grant access to his/her facebook information like email id, username, friends, posts etc. Once your website has been granted access and has all these information about the user it can allow the user’s to access protected pages on your website.


Creating a Facebook App

If your website is allowing login using facebook then your website is considered as an facebook app. So you have your website ready now its time to register you website as a facebook app. Follow this steps to register your website as an facebook app:

1. Click Here to visit Facebook apps page.
2. Click on “Create New App”.
3. Enter display name as your website title. Then choose category. Finally click “Create App”.
4. Now click on App name and you will enter app dashboard.
5. In the left panel click “Settings”.
6. Now enter your website domain name in the box “App Domains”.
7. Now click on “Add Platform” and then choose “website”. Now enter your website main url and mobile url.
8. Now click “Save Changes”. You have successfully registered your website as a facebook app.

Login with Facebook Button

Now we need to create a Login button for our website. Create a anchor element and point to “https://www.facebook.com/dialog/oauth?client_id={app-id}&redirect_uri={redirect-url}&scope={required-info-permssions}”

  • app-id: copy your facebook app id from app dashboard.
  • redirect-url: specify the url where the user will be redirect once he accepts for facebook login.
  • required-info-permissions: comma separated list of required information.

This is the code present in our live example:
index.php

<!doctype html>
<html>
    <head>
        <title>Facebook Login</title>
    </head>
    <body>
        <a href="https://www.facebook.com/dialog/oauth?client_id={app-id}&redirect_uri=http://labs.qnimate.com/facebook-login/dialog-box-redirect.php&scope=email,user_birthday">Click Here To Login Using Facebook</a>
    </body>
</html>

Now when user clicks on the link, he will be asked by facebook to confirm access to our app. Once the user agrees or disagrees he will be directed back to our redirect url specified.

Redirect URL Page

If the user accepts information access to our app then facebook passes a one time generated code in the query parameter of the redirect url. Otherwise facebook passes a custom error message. If user accepts then facebook generates a access token using which we can access all user information. But facebook doesn’t sent it to us directly in the redirect url due to security reasons. So we need to retrieve it from facebook servers using the one time generated code and app secret string.

A user can disallow information access to our app from facebook anytime. So the access token can also be used to retrieve weather user is still allowing access or not. In this case all our requests to facebook servers will result in error message.

So in our redirect page first we will retrieve the access token. Then we will store our token in session array, which will be used by all requests to our website to check if user is logged in or not. And also retrieve user information.

This is the code present in our live example:
dialog-box-redirect.php

<?php
   
    session_start();
   
    if(isset($_GET["code"]))
    {  
        $token_and_expire = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id={app-id}&redirect_uri={redirect-url}&client_secret={app-secret-string}&code=" . $_GET["code"]);
       
        parse_str($token_and_expire, $_token_and_expire_array);
       
       
        if(isset($_token_and_expire_array["access_token"]))
        {  
            $access_token = $_token_and_expire_array["access_token"];
            $_SESSION['fb_access_code'] = $access_token;
           
            header("Location: http://labs.qnimate.com/facebook-login/check.php");
                }
        else
        {  
            echo "\n An error accoured!!!!! \n";
            exit;
        }
    }
    else
    {
        echo "\n An error accoured!!!!! \n";
    }
   
?>
  • app-id: Found in app dashboard
  • redirect-url: same as passed earlier.
  • app-secret-string: found in app dashboard. Don’t share this string with anyone. This string is the reason for secure login.

Back to user

Now we have stored the access token in the user session. Now this access token will be used by all our web pages to check if user is logged in or not. And also for retrieving user information. In the above redirect page we redirect the user to another page in our website if login is successful.

This is the code present in our live example.
check.php

<?php
    session_start();
   
    if(isset($_GET["logout"]))
    {
        if($_GET["logout"] == "true")  
        {
            session_destroy();
            echo "You are logged out of this website";
            echo "<br><a href='index.php'>Click here to proceed to the sign in page</a>";
        }  
    }
    else if(isset($_SESSION["fb_access_code"]))
    {
        $user_information = file_get_contents("https://graph.facebook.com/me?access_token=" . $_SESSION["fb_access_code"] . "&fields=email,user_birthday");
        $user_information_array = json_decode($user_information, true);
       
        if(isset($user_information_array["email"]))
        {
            echo "Your email id is " . $user_information_array["email"] . " and you are logged in using facebook now !!!!";
            echo "<br><a href='check.php?logout=true'>Log Out</a>";
        }
        else
        {
            echo "Please login in using facebook";
            echo "<br><a href='index.php'>Click here to proceed to the sign in page</a>";  
        }
    }
    else
    {
        echo "Please login in using facebook";
        echo "<br><a href='index.php'>Click here to proceed to the sign in page</a>";
    }
?>

In the above code user can click logout to delete the access code from user session. Else the user can logout from facebook dashboard, in this case we will receive error message while making requests so we can assume user has logged out.


Conclusion

In this post we saw the secure way of retrieving user information and creating a login system using facebook graph api. Logging out facebook.com doesn’t make the access token invalid or logout from the app. For logging out from app you need to delete the cookie or disable app access from facebook dashboard. Thanks for reading.

Apr 3, 2014Narayan Prusty
Tabs Using HTML And CSS OnlyDisplaying And Highlighting Source code in HTML Page
Comments: 3
  1. marketin wheel
    4 years ago

    A Figure out what feature you need and find the one that
    will work perfect for you. The allergens in food are proteins that handle provoking an allergic
    reaction. They do not want to pay out money before
    they have even created a dime in revenue.

    ReplyCancel
  2. Ganar dinero con un blog
    6 years ago

    I feel that is among the such a lot important info for me.
    And i’m satisfied studying your article. But want to commentary on few normal things, The
    web site style is wonderful, the articles is actually great : D.
    Just right task, cheers

    ReplyCancel
  3. lubin
    6 years ago

    It’s going to be end of mine day, except before finish I am reading this
    impressive piece of writing to increase my knowledge.

    ReplyCancel

Leave a Reply to marketin wheel Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

Image8 years ago 3 Comments API, Web Developmentfacebook, login, oauth, php
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • What is OAuth?
  • What is Facebook Log In?
  • Creating a Facebook App
  • Login with Facebook Button
  • Redirect URL Page
  • Back to user
Related Articles
  • Twitter Cards Meta Tags Tutorial
  • Facebook Open Graph Meta Tags Tutorial
  • PageSpeed Insights API
  • URL Tracking Parameters and Its Negative Impact
  • Retrieving Social Shares, Likes And Comments Count Of A URL
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license