Facebook Oauth login flow with Flutter

I decided to give Flutter a deeper try than previously. But I encounter some troubles with authentication. So in this story I will share what I have done to implement Facebook authentication in my Flutter app with only dart code.

As you probably know Flutter is a mobile app SDK for building high-performance, high-fidelity, apps for iOS and Android, from a single codebase.

Let’s start!

Invoking the Login Dialog and setting the Redirect URL

What we want is a manually login flow for facebook. Here is the link to the facebook documentation. We need to call the facebook dialog page with our cliend_id and a redirect_uri.

This step gives us some informations that is in fact not the first step. We need a redirect_uri but we only have our app, so we will create a little http server inside our app, for that we will start with a little server which handles one request and shutdowns.

Here is the code:

If you execute this code and then go to http://localhost:8080/ you will see a page telling you ‘You can now close this window’ and if you reload the page you will see a page not found.

Next we need to open a browser and go to https://www.facebook.com/v2.8/dialog/oauth?client_id={app-id}&redirect_uri=http://localhost:8080/ you will need to change {app-id} by your app id.

So we will use one service provided by the Flutter framework called UrlLauncher.

Now we have to get the query param named code that is added by Facebook when they do the redirection to our url. We will modify our server a little to do that. And transform it in an usable function.

Almost the same functionality we had previously, plus getting the code from the query parameters and put this code inside a StreamController.

Let’s put all these pieces together!

We can pass to the second step of the oauth flow!

Exchanging Code for an Access Token

Here we just need to call this url with the code we get before and our app credential.

We will use the http package from pub for that task!

The response is a JSON that looks like that:

So we will wrap that in a dart object.

Now a quick resume of the code for this second step.

Before we can write an app we need one more thing! Write an utility class to call the Graph API. Here is something really basic:

It’s a basic call to an API in Dart. Now we can pass to the flutter part of the code :)

And Tadam! You have an app where you can authenticate your user with Facebook :)

You can also use almost the same workflow for other authentication service that supports oauth.

You can find the full source code of this here.

Don’t hesitate to follow me on twitter (@kevin_segaud) and clap if you have appreciate the article :)