Wednesday, April 23, 2014

Facebook Authentication in Perl with Mojolicious (Lite)

Below is the minimum you need in order to have a web app that provides Facebook authentication.

Although there are less than 100 lines of code (including comments), this is a complete Facebook application implemented in +Perl  , using the +Mojolicious web framework. It provides Facebook authentication and accesses user's Facebook username. Of course, with proper scope settings it could also access user's list of friends, the pages that the user manages, or many other interesting things that Facebook offers access to.

So, the complete app:

In order to make it work, you have to first create a Facebook application and then fill in the values for $config->{facebook}->{app_id} and $config->{facebook}->{secret}  with the values provided by Facebook on the application Settings page:

Also, you have to provide a Site URL to your Facebook app. This is the URL where the user will be redirected after Facebook authenticates him. In our app, the URL is  - of course, is not a valid domain, but an alias I made in /etc/hosts that points to the IP of the machine that runs our Mojo Lite app - Facebook seems to be OK with this URL.

After you have installed the dependencies:

You can start your app in dev mode by executing: morbo facebook

When you click on the Click here to authenticate with FB link, you (and your users) will be redirected to Facebook and presented with a screen like this

After you authorize the app to access all the scopes set on line 39, Facebook will redirect you back to your app. Note that this authorization phase is done just once - after that, every time you log in with that account, Facebook will simply redirect you to the app.

If you read this far and liked the article, get rid of your shyness and share it using the buttons on the left :)


Post a Comment