DEV Community

Cover image for How to authenticate to facebook with no gui, using python

Posted on

How to authenticate to facebook with no gui, using python

I saw that there is a lot of developers searching for how they can authenticate their users without using the usual workflow who need a gui and a login button to authenticate their users.

I did not find any articles or blogs talking about this except the official Facebook documentation, without much talking let's dive in to to the solution

Coding part

Our goal here is to make this script successfully python -ai app_id -cs client_secret -pi page_id.

You can find the app id in the in your app dashboard, as you can see in the picture below.

Image description

The client secret can be found in the settings then advanced after this search for the client search label.

Image description

Then enable login from devices, and enable the login from devices.

Image description

The following code python script is what you need, after execution a code will be generated and displayed in your terminal, be careful because this code is only available for 450 seconds.

import requests
import argparse

API_URL = ''

def parse_args(publish_post):
   parser = argparse.ArgumentParser()

   parser.add_argument('-pid', '--pageId', dest='pageid', action='store',
                       help='page id')
   parser.add_argument('-cs', '--clientsecret', dest='clientsecret', action='store',
                       help='client secret token')

   parser.add_argument('-ai', '--appid', dest='appid', action='store',
                       help='the id of the app')

   client_secret = parser.parse_args().clientsecret
   page_id = parser.parse_args().pageid
   app_id = parser.parse_args().appid
   return publish_post(app_id, client_secret, page_id)

def run():
   def publish_post(app_id, client_secret, page_id):
      params = {
        'access_token': f'{app_id}|{client_secret}',
        'scope': 'pages_manage_posts,public_profile' # permissions

      url = f'{API_URL}/device/login'
      res =, params=params).json()

      interval = res['interval']

      # poll for login
      # check if the user authorized our app or not
      data = {
         'access_token': f'{}|{args.token}',
         'code': res['code']
      url = f'{API_URL}/device/login_status'

      while True:
         res =, data=data).json()
            access_token = res['access_token']
         except KeyError:

      # generate a page access token
      params = {
         'fields': 'access_token',
         'access_token': access_token,
      url = f'{API_URL}/{page_id}'
      res = requests.get(url, params=params).json()
      print('page access token is', res['access_token'])

Enter fullscreen mode Exit fullscreen mode

If you want know more about this make sure to check the Facebook login for devices official documentation, remember that you will need to pass through the app review phase, click here to read more.

Discussion (0)