All Articles

Using Client Credential OAuth in n8n

Dipped my toe into the world of n8n recently. With most platforms, you run into something that doesn’t make a ton of sense. In this case, n8n currently doesn’t provide an option for setting the “client credentials” grant flow for OAuth authentication which is (still) used by a large number of services out there like some Twitter API calls. Luckily, using HTTP requests in a workflow like easily perform what a “client credential” based OAuth token would do if it were a configuration option.

Diagram of Twitter auth flow in n8n

Twitter’s authentication documentation says that for this authentication flow, we’ll need to make a request to https://api.twitter.com/oauth2/token with Basic authentication containing the API_KEY and API_SECRET_KEY of the application I’ll be authenticating with along with a query parameter of grant_type=client_credentials. Once the Node is created and ran successfully, the authentication token will be in a JSON object under the access_token key. The next Node can then use that token as a variable in a header like Authorization: Bearer {{$node["Get Twitter Auth"].json["access_token"]}}.

Here are the example Nodes that can be used in a workflow:

{
  "nodes": [
    {
      "parameters": {
        "authentication": "basicAuth",
        "requestMethod": "POST",
        "url": "https://api.twitter.com/oauth2/token",
        "options": {},
        "queryParametersUi": {
          "parameter": [
            {
              "name": "grant_type",
              "value": "client_credentials"
            }
          ]
        }
      },
      "name": "Get Twitter Auth",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        460,
        280
      ],
      "credentials": {
        "httpBasicAuth": {
          "id": "3",
          "name": "Twitter Basic credential"
        }
      }
    },
    {
      "parameters": {
        "url": "https://api.twitter.com/1.1/followers/list.json?cursor=-1&screen_name=tuckner&count=25",
        "options": {},
        "headerParametersUi": {
          "parameter": [
            {
              "name": "Authorization",
              "value": "=Bearer {{$node[\"Get Twitter Auth\"].json[\"access_token\"]}}"
            }
          ]
        }
      },
      "name": "Get Twitter Followers",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        660,
        280
      ]
    }
  ],
  "connections": {
    "Get Twitter Auth": {
      "main": [
        [
          {
            "node": "Get Twitter Followers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}