Skip to main content

What you’ll learn

  • Authenticate with Auth0 AI: configure Auth0 AI and obtain federated access tokens for Slack APIs.
  • Call external APIs securely: use the token to list Slack channels through a LlamaIndex tool.
  • Handle auth interruptions: enable dynamic user consent and reauthorization within chat flows.
Before getting started, make sure you have completed the following steps:
1

Create an Auth0 Account

To continue with this quickstart, you need to have an Auth0 account.
2

Create an Auth0 Application

Go to your Auth0 Dashboard to create a new Auth0 Application.
  • Navigate to Applications > Applications in the left sidebar.
  • Click the Create Application button in the top right.
  • In the pop-up select Regular Web Applications and click Create.
  • Once the Application is created, switch to the Settings tab.
  • Scroll down to the Application URIs section.
  • Set Allowed Callback URLs as: http://localhost:3000/auth/callback
  • Set Allowed Logout URLs as: http://localhost:3000
  • Click Save in the bottom right to save your changes.
3

Configure Google Social Integration

Set up a Google developer account that allows for third-party API calls by following the Google Social Integration instructions.
4

OpenAI Platform

  • https://mintlify.s3.us-west-1.amazonaws.com/auth0-genai-feat-add-diagrams-modal-with-steps/img/nextjs-light.svg Next.js
  • https://mintlify.s3.us-west-1.amazonaws.com/auth0-genai-feat-add-diagrams-modal-with-steps/img/fastapi-light.svg FastAPI

Getting started using AI

To get started quickly:
Clone auth0-lab/auth0-ai-js and navigate to examples/calling-apis/chatbot/app/(llamaindex) directory.
Then, integrate Auth0 AI docs into your preferred AI tool:

  • VS Code
  • Cursor
  • Claude Code
  • Claude
Create a .vscode/mcp.json file and add:
{
  "servers": {
    "Auth0 for AI Agents": {
      "type": "http",
      "url": "https://auth0.com/ai/docs/mcp"
    }
  }
}
To learn more, read the VS Code documentation.

or Follow manual steps

1

Configure Auth0 AI

First, you must install the SDK:
pip install auth0-ai-llamaindex
Then, you need to initialize Auth0 AI and set up the connection to request access tokens with the required Slack scopes.
./src/lib/auth0-ai.py
from auth0_ai_llamaindex.auth0_ai import Auth0AI
from flask import session

auth0_ai = Auth0AI()

with_slack = auth0_ai.with_token_vault(
    connection="sign-in-with-slack",
    scopes=["channels:read groups:read"],
    refresh_token=lambda *_args, **_kwargs:session["user"]["refresh_token"],
)
Here, the session is controlled by a Flask application instance. You may utilize any other framework or session store of your preference.
2

Integrate your tool with Slack

Wrap your tool using the Auth0 AI SDK to obtain an access token for the Slack API.
./src/lib/tools/list_channels.py
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from llama_index.core.tools import FunctionTool
from auth0_ai_llamaindex.token_vault import get_access_token_from_token_vault, TokenVaultError
from src.lib.auth0_ai import with_slack

def list_slack_channels_tool_function():
    # Get the access token from Auth0 AI
    access_token = get_access_token_from_token_vault()

    # Slack SDK
    try:
        client = WebClient(token=access_token)
        response = client.conversations_list(
            exclude_archived=True,
            types="public_channel,private_channel",
            limit=10
        )
        channels = response['channels']
        channel_names = [channel['name'] for channel in channels]
        return channel_names
    except SlackApiError as e:
        if e.response['error'] == 'not_authed':
            raise TokenVaultError("Authorization required to access the Token Vault API")

        raise ValueError(f"An error occurred: {e.response['error']}")

list_slack_channels_tool = with_slack(FunctionTool.from_defaults(
    name="list_slack_channels",
    description="List channels for the current user on Slack",
    fn=list_slack_channels_tool_function,
))
Now that the tool is protected, you can pass it your LlamaIndex agent.
./src/lib/agent.ts
from datetime import datetime
from llama_index.agent.openai import OpenAIAgent
from src.lib.tools.list_channels import list_slack_channels_tool

system_prompt = f"""You are an assistant designed to answer random user's questions.
**Additional Guidelines**:
- Today’s date for reference: {datetime.now().isoformat()}
"""

agent = OpenAIAgent.from_tools(
    tools=[
        # a tool with Token Vault access
        list_slack_channels_tool
        # ... other tools
    ],
    model="gpt-4o",
    system_prompt=system_prompt
    verbose=True,
)
3

Handle authentication redirects

Interrupts are a way for the system to pause execution and prompt the user to take an action —such as authenticating or granting API access— before resuming the interaction. This ensures that any required access is granted dynamically and securely during the chat experience. In this context, Auth0-AI SDK manages such authentication redirects integrated with the LLamaIndex SDK.

Server side

On the server side of your Flask application you will need to set up a route to handle the Chat API requests. This route will be responsible for forwarding the requests to the OpenAI API utilizing LlamaIndex’s SDK, that has been initialized with Auth0 AI’s protection enhancements for tools.When TokenVaultInterrupt error ocurrs, the server side will signal the front-end about the level access restrictions, and the front-end should prompt the user to trigger a new authorization (or login) request with the necessary permissions.
./src/app.py
from dotenv import load_dotenv
from flask import Flask, request, jsonify, session
from auth0_ai_llamaindex.auth0_ai import Auth0AI
from auth0_ai_llamaindex.token_vault import TokenVaultInterrupt
from src.lib.agent import agent

load_dotenv()
app = Flask(__name__)

@app.route("/chat", methods=["POST"])
async def chat():
    if "user" not in session:
        return jsonify({"error": "unauthorized"}), 401

    try:
        message = request.json.get("message")
        response = agent.achat(message)
        return jsonify({"response": str(response)})
    except TokenVaultInterrupt as e:
        return jsonify({"error": str(e.to_json())}), 403
    except Exception as e:
        return jsonify({"error": str(e)}), 500

Account Linking

If you're integrating with Slack, but users in your app or agent can sign in using other methods (e.g., a username and password or another social provider), you'll need to link these identities into a single user account. Auth0 refers to this process as Account Linking.Account Linking logic and handling will vary depending on your app or agent. You can find an example of how to implement it in a Next.js chatbot app here. If you have questions or are looking for best practices, join our Discord and ask in the #auth0-for-gen-ai channel.

How-Tos