HomeAuthorizationGeneric authorization

Generic Agent Authorization

In this guide, you’ll learn how to use Arcade to obtain user authorization for accessing third-party services, without using Arcade for tool execution or definition. We’ll use Google’s Gmail API as an example to demonstrate how to:

  • Get authorization tokens through Arcade
  • Handle user authentication flows
  • Use tokens with external services

This can be useful when you need to manage authorization flows in your application.

Prerequisites

  • Set up Arcade
  • Install the Arcade Client and the required libraries:
pip install arcadepy google-api-python-client google-auth-httplib2 google-auth-oauthlib

Import required libraries

First, let’s import all the libraries we’ll need:

from arcadepy import Arcade
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

Initialize the Arcade client

Create an instance of the Arcade client:

client = Arcade()  # Automatically finds the `ARCADE_API_KEY` env variable

Initiate an authorization request

Use client.auth.start to initiate the authorization process:

# Get this user ID from a trusted source, like your database or user management system
user_id = "[email protected]"
 
# Start the authorization process
auth_response = client.auth.start(
    user_id=user_id,
    provider="google",
    scopes=["https://www.googleapis.com/auth/gmail.readonly"],
)

Guide the user through authorization

If authorization is not completed, prompt the user to visit the authorization URL:

if auth_response.status != "completed":
    print("Please complete the authorization challenge in your browser:")
    print(auth_response.url)

Wait for the user to authorize the request

Use wait_for_completion() to wait for the user to authorize the request:

auth_response = client.auth.wait_for_completion(auth_response)

Use the obtained token

Once authorization is complete, you can use the obtained token to access the third-party service:

credentials = Credentials(auth_response.context.token)
gmail = build("gmail", "v1", credentials=credentials)
 
email_messages = (
    gmail.users().messages().list(userId="me").execute().get("messages", [])
)
 
print(email_messages)

Consider using the Arcade Google toolkit, which simplifies the process for retrieving email messages even further! The pattern described here is useful if you need to directly get a token to use with Google in other parts of your codebase.

How it works

By using client.auth.start and client.auth.wait_for_completion, you leverage Arcade to manage the OAuth flow for user authorization.

Arcade handles the authorization challenges and tokens, simplifying the process for you.

Next steps

Integrate this authorization flow into your application, and explore how you can manage different providers and scopes.