Building Scalable n8n Workflows: How to Use OAuth 2.0 for Multi-User Workflows

Building Scalable n8n Workflows: How to Use OAuth 2.0 for Multi-User Workflows

The greatest challenge for n8n has always been in credential reuse i.e. if you have a workflow connecting to an app, you can not pass the credentials dynamically. You will find each node can only use a static credential and this can’t be done dynamically

In the case you are building a Gmail manager, you will need to deploy a new agent for each Gmail account, or use multiple nodes with the user credentials. Not scalable

I dedicated tens of hours researching how to solve this and create one workflow that can be used within a whole organization without having to recreate it for each users credential in n8n AKA collecting external credentials for use in n8n

The solution? An oath workflow that allows users to log in with their own accounts and grant you permissions to what you need.

  1. n8n account
  2. Access to the google account property
  3. Google Console account for the client ID and Secret
  4. Knowledge on the HTTP node

OAuth 2.0 is an authorization framework that allows third-party applications to access user data from a service (like Google or Facebook) without exposing the user’s credentials. It works by delegating user authentication to the service that hosts the user account and authorizing third-party applications to access the user’s data with tokens instead of passwords.

Here’s how it typically works:

First, the application requests authorization from the user to access their data. If the user grants permission, the application receives an authorization grant. This grant is then exchanged for an access token by the application, which is presented to the resource server (e.g., the service hosting the user’s data) to access the requested information.

The access token is a short-lived credential that can be refreshed using a refresh token if the access token expires. OAuth 2.0 is widely used because it provides a secure and standardized way to handle authorization across different platforms and services.

We need a few things set up before we can build the app

  1. Google cloud project
  2. A simple code to implement the login page
  1. Go to the Google Cloud Console.
  2. Click Create Project and give it a name (e.g., “Google Analytics OAuth App”).
  3. Once the project is created, select it from the dashboard.
  1. In the left sidebar, go to APIs & Services > Library.
  2. Search for “Google Analytics API” and click Enable.
  1. Go to APIs & Services > OAuth Consent Screen.
  2. Choose External (for public apps) or Internal (for G Suite apps).
  3. Fill in the required details:
  4. Add the following scope:
  5. Save and continue.
  1. Go to APIs & Services > Credentials.
  2. Click Create Credentials and select OAuth Client ID.
  3. Choose Web Application as the application type.
  4. Add the Authorized Redirect URI:
  5. Click Create. You’ll receive a Client ID and Client Secret. Save these securely.

This code is a simple implementation of the web page that initiates the Google OAuth 2.0 flow for accessing Google Analytics data. Here’s a breakdown of how it works:

  • clientId: This is the unique identifier for your application, provided by Google when you create OAuth credentials in the Google Cloud Console.
const clientId = '188dig8qsgshm8e10omd0pi4vna44e6.apps.googleusercontent.com';
  • redirectUri: This is the URL where Google will send the authorization code after the user grants permission. It must match the redirect URI configured in your Google Cloud Console.
const redirectUri = 'https://dev.funautomations.io/webhook/oauth2-callback';

The authUrl is the URL that redirects the user to Google’s OAuth 2.0 authorization page. It includes the following parameters:

  • response_type=code: Specifies that the response should include an authorization code.
  • client_id: Your application’s client ID.
  • redirect_uri: The URL where Google will redirect the user after authorization.
  • scope: The permissions your app is requesting. In this case, it’s https://www.googleapis.com/auth/analytics.readonly, which allows read-only access to Google Analytics data.
  • access_type=offline: Requests a refresh token, which allows your app to obtain new access tokens without user interaction.
  • prompt=consent: Ensures the user is prompted to grant permissions, even if they’ve previously authorized the app.
const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=https://www.googleapis.com/auth/analytics.readonly&access_type=offline&prompt=consent`;

The code returns an HTML page with a styled “Login with Google” button. When the user clicks the button, they are redirected to the authUrl, which starts the OAuth flow.

  • Headers: The Content-Type header is set to text/html to indicate that the response is an HTML page.
  • Body: The HTML content includes:

– A title (Google Analytics OAuth2 Login).

– A styled button (Login with Google) that links to the authUrl.

– A footer with a help link.

return {
  headers: {
    'Content-Type': 'text/html'
  },
  body: `<!DOCTYPE html>
<html>
<head>
<title>Google Analytics Login</title>
<style>
    /* CSS styles for the page */
</style>
</head>
<body>
    <div class="container">
        <h1>Google Analytics OAuth2 Login</h1>
        <p>To proceed, click the button below to log in with your Google account:</p>
        <a href="${authUrl}" class="cta-button">Login with Google</a>
        <footer>
            <p>Need help? <a href="https://support.google.com/analytics">Visit Google Analytics Help</a></p>
        </footer>
    </div>
</body>
</html>`
};
  1. User Clicks the Button: The user is redirected to Google’s authorization page, where they log in and grant permissions.
  2. Google Redirects with Code: After authorization, Google redirects the user to the redirectUri with an authorization code.
  3. Exchange Code for Tokens: Your server must exchange the authorization code for an access token and refresh token by making a POST request to Google’s token endpoint:
POST https://oauth2.googleapis.com/token

Include the client_id, client_secret, redirect_uri, code, and grant_type=authorization_code in the request.

4. Access Google Analytics: Use the access token to call the Google Analytics API and retrieve data.

With the generated access token, we can use this in the header as Authorization= Bearer Access_token and make requests as though we were on the actual credentials

  1. Use a variable path for the main webhook URL to keep track of whom logged in. This can be done via a variable with a unique identifier such as the email id.
  2. Have a database to store all the codes, access tokens we get
  3. If possible, create a simple workflow to encrypt these tokens before we can store them

If you would like to implement this in your business, feel free to reach out via email on kimothozacharia5@gmail.com

Happy productivity!