Facebook OAuth: Authenticate with Facebook in Codeigniter

How to Authenticate with Facebook ? In this post i would like to show how we can get authenticate with Facebook using codeigniter. Facebook OAuth API allow to authenticate user into web applications by using their facebook account. Follow me i will show you step by step how we can achieve this.

Get Facebook OAuth Credentials:

Before integrating Facebook authentication into our application, we need to create some Facebook OAuth credentials.To create oauth credential, Simple go to Facebook Developer Console and create new app and all oauth credentials.

Dashboard Facebook Developer

Create New App:

Simply Go to My Apps and click on Create New App.

Facebook OAuth: Facebook Create App

App Settings:

After creating new app go to the basic setting of the app and enter all details that required.

Facebook App Basic Setting

Setting Up in Codeigniter:

After Getting app id and secret key from Facebook you need to install  and setup Facebook  SDK into codeigniter application.

Installing Facebook SDK via Composer:

To install Facebook SDK via composer you need to run command from codeigniter project root directory as i am showing Below.


composer require Facebook/graph-sdk

Controller Creation:

Next, create a controller named FacebookLoginController.php inside application/controller directory and write below code.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class FacebookLoginController extends CI_Controller {
public function __construct()
{
parent::__construct();
}

Public function index()
{
$fb = new Facebook\Facebook([
'app_id'=>'APP_ID', /* Replace with your app id */
'app_secret'=>'SECRET_KEY', /* Replace with your secret key */
'default_graph_version'=>'v2.2',
]);

$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; /* Optional permissions */
$loginUrl = $helper->getLoginUrl('https://localhost/myapp/FacebookLoginController/fbcallback', $permissions);
echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';
}

Public function fbcallback()
{
$fb = new Facebook\Facebook([
'app_id'=>'APP_ID', /* Replace with your app id */
'app_secret'=>'SECRET_KEY', /* Replace with your secret key */
'default_graph_version'=>'v2.2',
]);

$helper = $fb->getRedirectLoginHelper();

try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
/* When Graph returns an error */
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
/* When validation fails or other local issues */
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}

if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}

/* Logged in */
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());

/* The OAuth 2.0 client handler helps us manage access tokens */
$oAuth2Client = $fb->getOAuth2Client();

/* Get the access token metadata from /debug_token */
$tokenMetadata = $oAuth2Client->debugToken($accessToken);

/* Validation (these will throw FacebookSDKException's when they fail) */
$tokenMetadata->validateAppId('1933290566759752'); // Replace {app-id} with your app id
/* If you know the user ID this access token belongs to, you can validate it here */
/*$tokenMetadata->validateUserId('123'); */
$tokenMetadata->validateExpiration();

if (! $accessToken->isLongLived()) {
/* Exchanges a short-lived access token for a long-lived one */
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $e->getMessage() . "</p>\n\n";
exit;
}
}
}
}
This example simply authenticate with Facebook OAuth. You can use this for your application’s login system by checking user if new and storing necessary data into your database.
Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help!

 

I am Hitesh from Jamshedpur (India). I have been working as a Web Application Developer from last 4+ years. I love diverse and attention catching web presence for a variety of users. Also I love to learn new things in Web Development.

Tags: , , , ,