Archive for July, 2010

Validating Facebook Connect API cookies in perl

Thursday, July 29th, 2010

I didn’t find a sample code for validating the Facebook Connect API cookies in perl from Google so here is one. The CGI::Cookie interface is a bit tricky to use with the Facebook cookie parsing as it wants to split the cookie contents automatically on each ampersand, but here is how we translated the given sample PHP code to perl:

use CGI::Cookie;
use URI;
use Digest::MD5;

my $app_id = "136913766343238";
my $secret = "dbct84ca3d1fbs44428r02bdbag9193e";
my $cookie_header = $ENV{COOKIE};

my %cookies = CGI::Cookie->parse( $cookie_header );
my $cookie_object = $cookies{'fbs_' . $app_id};

die unless $cookie_object;

my $cookie = join "&", $cookie_object->value;
$cookie =~ s/^[\\"]*(.*?)[\\"]*$/$1/;

my $uri = URI->new("", "http");
$uri->query( $cookie );
my %params = $uri->query_form;
my $sig = delete $params{sig};
my $payload = join '', map { $_ .'='. $params{$_} } sort keys %params;

die unless Digest::MD5::md5_hex( $payload . $secret ) eq $sig;

my $valid_facebook_user_id = $params{uid};

Splitting the query parameters would have been pretty easy to do with a regexp but as the sample PHP code uses it’s query parser, I thought using a valid query parser from URI would be a safe and easy bet.