Facebook::OpenGraph – logging in to a Perl application

Getting a Perl application to talk to the Facebook API was not an enjoyable experience, mostly due to my lack of experience with Facebook’s terminology and a basic understanding of how OAuth works.

Ignorance never stops me! So when I wanted to allow visitors to log in to my Perl application via Facebook, I just started hacking away until I got everything working. I am scheduled to give a talk about this at the 2016 Dutch Perl Workshop, you can download the Presentation PDF.

My notes:

Install the Furl::HTTP and Facebook::OpenGraph modules.

Register the your application with Facebook to get your App ID and App Secret.

I broke this process up into two scripts, a ‘login’ script that acts as a landing page for incoming visitors and the application itself. The login script is going to catch the incoming request and immediately forward the visitor to the Facebook authorization page with a callback pointed at the program (index.cgi).

use Furl::HTTP;
use Facebook::OpenGraph; 
use strict;
use CGI;
my $q = new CGI;
   $q->autoEscape(0);
   $q->charset('utf8');
my $fb = Facebook::OpenGraph->new(+{
      version => 'v2.5'
    , app_id => '1234567890123456' 
    , secret => '2b6928c1283475f434a54bf45371'
    , ua => Furl::HTTP->new(capture_request => 1)
    , json => JSON->new->utf8
    , redirect_uri => 'http://applicationwebsite.com/app/index.cgi'
    });
 
my $auth_url = $fb->auth_uri(+{
       display => 'page' 
     , response_type => 'code'
     , scope => [qw/email/]
    });
print "Content-type: text/html\n\n";
print $q->redirect($auth_url);
exit;

This script takes an incoming visitor and generates an authorization URL for Facebook and then redirects the visitor directly to that Authorization URL. The ‘scope’ of my app is only asking for basic user information, no special permissions are being requested. If I wanted other, more esoteric, user information I would need to ask for specific approval to access that information.

You can see how to decode the information that gets sent to the callback URL, refer to the contents of the Presentation PDF.

 

Spread the love