In chatbot scenarios, it is often required to perform some sort of user authentication and authorization. For example, the bot might be doing travel reservations on behalf of the user so it needs the proper credentials to do so.

The Microsoft Bot Framework has some helpers to implement user authentication, for example, the SigninCard. There is also example Node.js code and C# code for authenticating the user. All the approaches work and can be leveraged, but are based on “external authentication flow” meaning performing the authentication outside of the chat context (for example, in a Web browser).

The Facebook Messenger offers a feature where you can perform the user authentication within the Facebook Messenger experience and this is called Account Linking.

In this post, I am showing a Node.js demo bot implementation found from GitHub that implements the Facebook Messenger Account Linking on top of the Microsoft Bot Framework.

User Experience Demo

See below a looping GIF that shows what the user experience is on an iPhone within the Facebook Messenger app.


Technical Details

On a high level, the account linking flow could be depicted as below:

Account Linking Sequence

In the sample code, the numbered sequences are handled as follows:

  1. On this line we listen when user’s message is link account and consider that as the trigger for the flow
  2. Since the button is Facebook-specific, we need to construct a Facebook-specific message to send it like this
  3. User clicks the button within the chat
  4. The Website is served as static assets with these code lines so the index page is this one
  5. User does authentication (in this sample, just types in a username)
  6. When user clicks the continue button in the index page, we set the page source to a URL handled in the bot code
  7. We pick up the username in the bot code and redirect to the URL given by Facebook
  8. The Account Linking Webhook event is handled here
  9. We store the username and inform the user

To make Facebook route the Account Linking events handled in step 8., you must subscribe to the messaging_account_linking event (instructions here).