Use Auth0 SDKs to fetch access tokens for social and enterprise identity providers from Auth0’s Token Vault. Using these access tokens, AI agents integrated with the application can call third-party APIs to perform tasks on the user’s behalf. By the end of this quickstart, you should have an AI application integrated with Auth0 that can:
  1. Retrieve access tokens for a Google social connection.
  2. Integrate with an AI agent to call Google APIs.

Pick your tech stack

Prerequisites

Before getting started, make sure you have completed the following steps:
1

Create an Auth0 Account and a Dev Tenant

To continue with this quickstart, you need an Auth0 account and a Developer Tenant.
2

Create an Auth0 Application

Create and configure an Auth0 Application with the following properties:
  • Type: Regular Web
  • Allowed Callback URLs: http://localhost:3000/auth/callback
  • Allowed Logout URLs: http://localhost:3000
To learn more about Auth0 applications, read Applications.
3

Enable Token Exchange Grant

Enable the Token Exchange Grant for your Auth0 Application. Go to Applications > [Your Application] > Settings > Advanced > Grant Types and enable the Token Exchange grant type.
4

Configure Google Social Connection

Set up a Google developer account that allows for third-party API calls following the Google Sign-in and Authorization instructions.
5

OpenAI Platform

Prepare Next.js app

Recommended: To use a starter template, clone the Auth0 AI samples repository:
git clone https://github.com/auth0-samples/auth0-ai-samples.git
cd auth0-ai-samples/authenticate-users/langchain-next-js

Install dependencies

In the root directory of your project, install the following dependencies:
  • @auth0/ai-langchain: Auth0 AI SDK for LangChain built for GenAI applications powered by LangChain.
  • @langchain/langgraph: For building stateful, multi-actor applications with LLMs.
  • langchain: The LangChain library.
  • @langchain/core: LangChain core libraries.
  • @langchain/openai: OpenAI provider for LangChain.
  • @langchain/community: LangChain community integrations.
  • langgraph-nextjs-api-passthrough: API passthrough for LangGraph.
npm install @auth0/ai-langchain@3 @langchain/community@0.3 @langchain/core@0.3 @langchain/langgraph@0.3 @langchain/openai@0.6 langchain@0.3 langgraph-nextjs-api-passthrough@0.1

Update the environment file

Copy the .env.example file to .env.local and update the variables with your Auth0 credentials. You can find your Auth0 domain, client ID, and client secret in the application you created in the Auth0 Dashboard.

Get access tokens for others APIs

Use the Auth0 AI SDK for LangChain to get access tokens for third-party APIs.

Set up Token Vault for Google social connection

Set up the Auth0 AI SDK for a Google Social Connection. This allows you to get access tokens for a Google social connection using Token Vault:
  • connection: pass in the name of the connection you want the user to sign up for/log into.
  • scopes: pass in the scopes for the service you want to get access to.
Create a file at src/lib/auth0-ai.ts and instantiate a new Auth0 AI SDK client:
src/lib/auth0-ai.ts
import { Auth0AI, getAccessTokenForConnection } from "@auth0/ai-langchain";

// Get the access token for a connection via Auth0
export const getAccessToken = async () => getAccessTokenForConnection();

const auth0AI = new Auth0AI();

// Connection for Google services
export const withGoogleConnection = auth0AI.withTokenForConnection({
  connection: "google-oauth2",
  scopes: ["https://www.googleapis.com/auth/gmail.readonly"],
});

Pass credentials to the tools

Update the /src/lib/auth0.ts file with the following code:
src/lib/auth0.ts
//...
//... existing code
// Get the refresh token from Auth0 session
export const getRefreshToken = async () => {
  const session = await auth0.getSession();
  return session?.tokenSet?.refreshToken;
};
Update the /src/app/api/chat/[..._path]/route.ts file with the following code. The refreshToken will be passed to your LangGraph agent so we can use it from the Auth0 AI SDK to get Google access tokens from the server.
src/app/api/chat/[..._path]/route.ts
import { initApiPassthrough } from "langgraph-nextjs-api-passthrough";

import { getRefreshToken } from "@/lib/auth0";

export const { GET, POST, PUT, PATCH, DELETE, OPTIONS, runtime } =
  initApiPassthrough({
    apiUrl: process.env.LANGGRAPH_API_URL,
    baseRoute: "chat/",
    bodyParameters: async (req, body) => {
      if (
        req.nextUrl.pathname.endsWith("/runs/stream") &&
        req.method === "POST"
      ) {
        return {
          ...body,
          config: {
            configurable: {
              _credentials: {
                refreshToken: await getRefreshToken(),
              },
            },
          },
        };
      }

      return body;
    },
  });

Use access token to call APIs from a tool

Once the user is authenticated, you can fetch an access token from the Token Vault using the Auth0 AI SDK. In this example, we fetch an access token for a Google social connection. Once you’ve obtained the access token for a connection, you can use it with an AI agent to fetch data during a tool call and provide contextual data in its response.In this example, we will use the GmailSearch from the @langchain/community tools. This tool will use the access token provided by Token Vault to query for emails.
src/lib/agent.ts
//...
import { GmailSearch } from "@langchain/community/tools/gmail";
import { getAccessToken, withGoogleConnection } from "./auth0-ai";

//... existing code

// Provide the access token to the Gmail tools
const gmailParams = {
  credentials: {
    accessToken: getAccessToken,
  },
};

const tools = [
  //... existing tools
  withGoogleConnection(new GmailSearch(gmailParams)),
];
//... existing code
export const agent = createReactAgent({
  llm,
  tools: new ToolNode(tools, {
    // Error handler must be disabled in order to trigger interruptions from within tools.
    handleToolErrors: false,
  }),
  // Modify the stock prompt in the prebuilt agent.
  prompt: AGENT_SYSTEM_TEMPLATE,
  store,
  checkpointer,
});
You need to obtain an API Key from OpenAI or another provider to use an LLM. Add the API key to your environment variables:
.env.local
# ...
# You can use any provider of your choice supported by Vercel AI
OPENAI_API_KEY="YOUR_API_KEY"

Add step-up authorization

When you try to use the tool, the application requests any additional Google scopes that are required but not yet authorized. This process is called step-up authorization.Let us implement step-up authorization.Install the Auth0 AI Components for Next.js to get the required UI components:
npx @auth0/ai-components add FederatedConnections
Add a new file, src/components/auth0-ai/FederatedConnections/FederatedConnectionInterruptHandler.tsx, with the following code:
src/components/auth0-ai/FederatedConnections/FederatedConnectionInterruptHandler.tsx
import { FederatedConnectionInterrupt } from "@auth0/ai/interrupts";
import type { Interrupt } from "@langchain/langgraph-sdk";

import { EnsureAPIAccess } from "@/components/auth0-ai/FederatedConnections";

interface FederatedConnectionInterruptHandlerProps {
  interrupt: Interrupt | undefined | null;
  onFinish: () => void;
}

export function FederatedConnectionInterruptHandler({
  interrupt,
  onFinish,
}: FederatedConnectionInterruptHandlerProps) {
  if (
    !interrupt ||
    !FederatedConnectionInterrupt.isInterrupt(interrupt.value)
  ) {
    return null;
  }

  return (
    <div key={interrupt.ns?.join("")} className="whitespace-pre-wrap">
      <EnsureAPIAccess
        mode="popup"
        interrupt={interrupt.value}
        onFinish={onFinish}
        connectWidget={{
          title: "Authorization Required.",
          description: interrupt.value.message,
          action: { label: "Authorize" },
        }}
      />
    </div>
  );
}
Now, update the src/components/chat-window.tsx file to include the FederatedConnectionInterruptHandler component:
src/components/chat-window.tsx
//...
import { FederatedConnectionInterruptHandler } from '@/components/auth0-ai/FederatedConnections/FederatedConnectionInterruptHandler';

//... existing code
export function ChatWindow(props: {
  //... existing code
}) {
  const [threadId, setThreadId] = useQueryState('threadId');
  const [input, setInput] = useState('');
  const chat = useStream({
    apiUrl: props.endpoint,
    assistantId: 'agent',
    threadId,
    onThreadId: setThreadId,
    onError: (e: any) => {
      console.error('Error: ', e);
      toast.error(`Error while processing your request`, { description: e.message });
    },
  });
  //... existing code
  return (
    <StickToBottom>
      <StickyToBottomContent
        className="absolute inset-0"
        contentClassName="py-8 px-2"
        content={
          chat.messages.length === 0 ? (
            <div>{props.emptyStateComponent}</div>
          ) : (
            <>
              <ChatMessages
                aiEmoji={props.emoji}
                messages={chat.messages}
                emptyStateComponent={props.emptyStateComponent}
              />
              <div className="flex flex-col max-w-[768px] mx-auto pb-12 w-full">
                <FederatedConnectionInterruptHandler interrupt={chat.interrupt} onFinish={() => chat.submit(null)} />
              </div>
            </>
          )
        }
        {/* ... existing code */}
      ></StickyToBottomContent>
    </StickToBottom>
  );
}

Test your application

Start the application with npm run all:dev. Then, navigate to http://localhost:3000.
This will open the LangGraph Studio in a new tab. You can close it as we won’t require it for testing the application.
If you are already logged in, make sure to log out and log back in using Google. Then, ask your AI Agent to fetch emails from your Gmail account!That’s it! You successfully integrated integrated third-party API access using Token Vault into your project.Explore the example app on GitHub.

Next steps

You have successfully added the ability to get access tokens for tool calling to your application. For next steps: