> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# User Authentication

> Learn how Auth0 for AI Agents enables AI agents to seamlessly authenticate users.

export const DownloadQuickstartButton = ({category, framework, label = "Download Sample"}) => {
  const [isDownloading, setIsDownloading] = useState(false);
  const githubRepo = 'auth0-samples/auth0-ai-samples';
  const filename = `${category}-${framework}-sample.zip`;
  const downloadSample = () => {
    setIsDownloading(true);
    const downloadUrl = `https://github.com/${githubRepo}/releases/latest/download/${filename}`;
    window.open(downloadUrl, '_blank');
    setTimeout(() => setIsDownloading(false), 1000);
  };
  return <div className="download-button-container">
      <button onClick={downloadSample} disabled={isDownloading} className={`download-button ${isDownloading ? 'downloading' : ''}`} aria-label={`Download ${category} ${framework} sample code`}>
        {isDownloading ? <>
            <svg className="download-spinner" width="16" height="16" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" fill="none" strokeDasharray="31.416" strokeDashoffset="31.416">
                <animate attributeName="stroke-dasharray" dur="2s" values="0 31.416;15.708 15.708;0 31.416" repeatCount="indefinite" />
                <animate attributeName="stroke-dashoffset" dur="2s" values="0;-15.708;-31.416" repeatCount="indefinite" />
              </circle>
            </svg>
            Downloading...
          </> : <>
            <Icon icon="download" color="white" />
            {label}
          </>}
      </button>
    </div>;
};

export const AccountAndAppSteps = ({applicationType = "Regular Web Applications", callbackUrl = "http://localhost:3000/auth/callback", logoutUrl = "http://localhost:3000", appCreation = true, allowedWebOrigins, copyDomain, enableTokenVaultGrant = false, enableRefreshTokenGrant = false, enableAllowRefreshTokenRotation = undefined}) => {
  const steps = [<Step title="Create an Auth0 Account">
      To continue with this quickstart, you need to have an{" "}
      <a href="https://auth0.com/signup?onboard_app=auth_for_aa&amp;ocid=701KZ000000cXXxYAM-aPA4z0000008OZeGAM" target="_blank">
        Auth0 account.
      </a>
    </Step>];
  if (appCreation) {
    steps.push(<Step title="Create an Auth0 Application">
        Go to your{" "}
        <a href="https://manage.auth0.com/dashboard" target="_blank">
          Auth0 Dashboard
        </a>{" "}
        to create a new Auth0 Application.
        <ul>
          <li>
            Navigate to <a href="https://manage.auth0.com/#/applications" target="_blank"><strong>Applications {">"} Applications</strong></a> in the
            left sidebar.
          </li>
          <li>
            Click the <strong>Create Application</strong> button in the top
            right.
          </li>
          <li>
            In the pop-up select <strong>{applicationType}</strong> and click{" "}
            <strong>Create</strong>.
          </li>
          <li>
            Once the Application is created, switch to the{" "}
            <strong>Settings</strong> tab.
          </li>
          {copyDomain && <li>
              Copy the <strong>Domain</strong> from the{" "}
              <strong>Basic Information</strong> section to your clipboard.
            </li>}
          <li>
            Scroll down to the <strong>Application URIs</strong> section.
          </li>
          <li>
            Set Allowed Callback URLs as: <code>{callbackUrl}</code>
          </li>
          {logoutUrl && <li>
              Set Allowed Logout URLs as: <code>{logoutUrl}</code>
            </li>}
          {allowedWebOrigins && <li>
              Set Allowed Web Origins as: <code>{allowedWebOrigins}</code>
            </li>}
          {enableAllowRefreshTokenRotation !== undefined && <li>
              Scroll down to the <strong>Refresh Token Rotation</strong> section and {enableAllowRefreshTokenRotation === true ? "enable" : "disable"} the <strong>Allow Refresh Token Rotation</strong> option.
            </li>}
          {enableTokenVaultGrant && !enableRefreshTokenGrant && <li>
              Scroll down and expand the <strong>Advanced</strong> section. Switch to the <strong>Grant Types</strong> tab and enable the <strong>Token Vault</strong> grant type.
            </li>}
          {enableTokenVaultGrant && enableRefreshTokenGrant && <li>
              Scroll down and expand the <strong>Advanced</strong> section. Switch to the <strong>Grant Types</strong> tab and enable the <strong>Token Vault</strong> and <strong>Refresh Token</strong> grant types.
            </li>}
          <li>
            Click <strong>Save</strong> in the bottom right to save your
            changes.
          </li>
        </ul>
        To learn more about Auth0 applications, read{" "}
        <a href="https://auth0.com/docs/get-started/applications" target="_blank">
          Applications
        </a>
        .
      </Step>);
  }
  return steps;
};

export const Prerequisites = ({callbackUrl = "http://localhost:3000/auth/callback", logoutUrl = "http://localhost:3000"}) => {
  return <>
      <Heading level={3} id="prerequisites">
        Prerequisites
      </Heading>
      Before getting started, make sure you have completed the following steps:
      <Steps>{AccountAndAppSteps({
    callbackUrl,
    logoutUrl
  })}</Steps>
    </>;
};

Authentication is the process of proving a user's identity before granting them access to a resource. In this quickstart, you'll learn how to bring [Universal Login](https://auth0.com/docs/authenticate/login/auth0-universal-login) to your AI agent and leverage OAuth 2.0 and OpenID Connect to securely authenticate users.

When a user authenticates with an identity provider through Auth0, Auth0 can pass user information in an ID token to an application or AI agent to deliver a personalized experience. For example, a chatbot can greet a user with their name and display relevant information based on the user's profile.

By the end of this quickstart, you should have an application that can:

* Sign up and log in using a username and password or a Google account.
* Authenticate and authorize users using OAuth 2.0 and OpenID Connect.

## Pick your tech stack

<Tabs>
  <Tab title="Next.js" icon="https://mintlify-assets.b-cdn.net/auth0/next-js.svg">
    <Prerequisites />

    <Tabs>
      <Tab title="Use sample app (recommended)">
        ### Download sample app

        Start by downloading and extracting the sample app. Then open in your preferred IDE.

        <DownloadQuickstartButton category="authenticate-users" framework="vercel-ai-next-js" />

        ### Install packages

        Ensure you have `npm` installed or follow the instructions to [install npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) in its documentation.
        In the root directory of your project, install the required packages:

        ```bash wrap lines theme={null}
        npm install
        ```

        ### Create your environment file

        In the root directory of your project, create a new `.env.local` file and add the following content:

        ```bash .env.local wrap lines theme={null}
        APP_BASE_URL='http://localhost:3000'
        AUTH0_SECRET='random 32 byte value'
        AUTH0_DOMAIN='<your-auth0-domain>'
        AUTH0_CLIENT_ID='<your-auth0-application-client-id>'
        AUTH0_CLIENT_SECRET='<your-auth0-application-client-secret>'
        ```

        To get your Auth0 application's `AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, and `AUTH0_CLIENT_SECRET`, navigate to <strong>Applications > Applications </strong> in the Auth0 Dashboard and select your client application. You'll find these values in the **Basic Information** section at the top.
        Copy each value to the matching setting.

        Next, run this command to generate a random 32 byte value and copy it to the `AUTH0_SECRET` field:

        ```bash generate random 32 byte value theme={null}
        openssl rand -hex 32
        ```

        ### Run your application

        Run this command to start your server:

        ```bash wrap lines theme={null}
        npm run dev
        ```

        Visit the URL `http://localhost:3000` in your browser.

        You will see:

        <Frame>
          <img src="https://mintlify.s3.us-west-1.amazonaws.com/auth0-genai/img/user_authentication_quickstart_login_screen.png" alt="Auth0 login screen" />
        </Frame>

        Sign up for your application to create a new user account. You will then see a welcome message with your username. You can sign in with that account on future visits.
      </Tab>

      <Tab title="Integrate into your app">
        ### Install Auth0 Next.js SDK

        In the root directory of your project, install the [Auth0 Next.js SDK](https://github.com/auth0/nextjs-auth0):

        ```bash wrap lines theme={null}
        npm i @auth0/nextjs-auth0@4
        ```

        ### Add log in to your application

        Secure your application using the Auth0 Next.js SDK.

        #### Create your environment file

        In the root directory of your project, create or add the following content to your `.env.local` file:

        ```bash .env.local wrap lines theme={null}
        APP_BASE_URL='http://localhost:3000'
        AUTH0_SECRET='random 32 byte value'
        AUTH0_DOMAIN='<your-auth0-domain>'
        AUTH0_CLIENT_ID='<your-auth0-application-client-id>'
        AUTH0_CLIENT_SECRET='<your-auth0-application-client-secret>'
        ```

        Access your `AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, and `AUTH0_CLIENT_SECRET` by viewing the Auth0 Application that you created in the Auth0 Dashboard and navigating to the Basic Information section at the top of the Settings tab.
        Copy each value to the matching setting.

        Next, run this command to generate a random 32 byte value and copy it to the `AUTH0_SECRET` field.

        ```bash generate random 32 byte value theme={null}
        openssl rand -hex 32
        ```

        #### Create the Auth0 client

        Create a new file in the `src/lib` directory and name it `auth0.ts`. Add the following code to create a new Auth0 client:

        ```tsx src/lib/auth0.ts wrap lines theme={null}
        import { Auth0Client } from "@auth0/nextjs-auth0/server";

        // Create an Auth0 Client.
        export const auth0 = new Auth0Client();
        ```

        The Auth0 client provides methods for handling authentication, sessions, and user data.

        #### Add the authentication middleware

        The middleware intercepts incoming requests and applies Auth0's authentication logic. Create a new file in the `src` directory and name it `middleware.ts` or update your existing middleware file. Add the following code to the file:

        ```tsx src/middleware.ts wrap lines theme={null}
        import { NextRequest, NextResponse } from "next/server";
        import { auth0 } from "./lib/auth0";

        export async function middleware(request: NextRequest) {
          const authRes = await auth0.middleware(request);

          // Authentication routes — let the Auth0 middleware handle it.
          if (request.nextUrl.pathname.startsWith("/auth")) {
            return authRes;
          }

          const { origin } = new URL(request.url);
          const session = await auth0.getSession(request);

          // User does not have a session — redirect to login.
          if (!session) {
            return NextResponse.redirect(`${origin}/auth/login`);
          }
          return authRes;
        }

        export const config = {
          matcher: [
            /*
             * Match all request paths except for the ones starting with:
             * - _next/static (static files)
             * - _next/image, images (image optimization files)
             * - favicon.ico, sitemap.xml, robots.txt (metadata files)
             * - $ (root)
             */
            "/((?!_next/static|_next/image|images|favicon.[ico|png]|sitemap.xml|robots.txt|$).*)",
          ],
        };
        ```

        #### Add Log in and Sign up buttons

        Use the following code example to check if the user is signed in or not:
        It will display the **Sign up** or **Log in** buttons without a user session. If a user session exists, the app displays a welcome message with the user's name.

        ```tsx src/app/page.tsx wrap lines highlight={5,7-27, 36} theme={null}
        //...
        import { auth0 } from "@/lib/auth0";

        export default async function Home() {
          const session = await auth0.getSession();

          if (!session) {
            return (
              <div className="flex flex-col items-center justify-center min-h-[50vh] my-auto gap-4">
                <h2 className="text-xl">You are not logged in</h2>
                <div className="flex gap-4">
                  <Button asChild variant="default" size="default">
                    <a href="/auth/login" className="flex items-center gap-2">
                      <LogIn />
                      <span>Login</span>
                    </a>
                  </Button>
                  <Button asChild variant="default" size="default">
                    <a href="/auth/login?screen_hint=signup">
                      <UserPlus />
                      <span>Sign up</span>
                    </a>
                  </Button>
                </div>
              </div>
            );
          }

          //... existing code

          // applicable only if you are using the starter template
          return (
            <ChatWindow
              endpoint="api/chat"
              emoji="🤖"
              placeholder={`Hello ${session?.user?.name}, I'm your personal assistant. How can I help you today?`}
              emptyStateComponent={InfoCard}
            />
          );
        }
        ```

        ### Run your application

        Start your app, typically with this command:

        ```bash wrap lines theme={null}
        npm run dev
        ```

        Visit your app in the browser, typically at `http://localhost:3000`.

        You will see:

        <Frame>
          <img src="https://mintlify.s3.us-west-1.amazonaws.com/auth0-genai/img/user_authentication_quickstart_login_screen.png" alt="Auth0 login screen" />
        </Frame>

        Sign up to your application to create a new user account. You will then see a welcome message with your user name. You can sign in with that account on future visits.

        ### View a complete example

        Want to see how it all comes together? Explore or clone the fully implemented sample application on [GitHub](https://github.com/auth0-samples/auth0-ai-samples/tree/main/authenticate-users/vercel-ai-next-js).
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="FastAPI" icon="https://mintlify-assets.b-cdn.net/auth0/FastAPI.svg">
    <Prerequisites callbackUrl="http://localhost:8000/api/auth/callback" logoutUrl="http://localhost:5173" />

    ### Download sample app

    Start by downloading and extracting the sample app. Then open in your preferred IDE.

    <DownloadQuickstartButton category="authenticate-users" framework="langchain-fastapi-py" />

    The project is divided into these two folders:

    * `backend`: contains the backend code for the web application, an API written in Python using FastAPI and the LangGraph agent.
    * `frontend`: contains the frontend code for the web application written in React as a Vite Single Page App (SPA).

    ### Install backend packages

    In the `backend` directory of your project, install the required packages using your preferred package manager, such as `uv`. You can follow the instructions to [install uv](https://docs.astral.sh/uv/getting-started/installation/) in its documentation.

    ```bash wrap lines theme={null}
    cd backend
    uv sync
    ```

    ### Create your environment file

    In the `backend` directory of your project, create a new file and name it `.env` and add the following content:

    ```bash .env wrap lines theme={null}
    APP_BASE_URL='http://localhost:8000'
    AUTH0_SECRET='random 32 byte value'
    AUTH0_DOMAIN='<your-auth0-domain>'
    AUTH0_CLIENT_ID='<your-auth0-application-client-id>'
    AUTH0_CLIENT_SECRET='<your-auth0-application-client-secret>'
    ```

    Access your `AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, and `AUTH0_CLIENT_SECRET` by viewing the Auth0 Application that you created in the Auth0 Dashboard and navigating to the Basic Information section at the top of the Settings tab.
    Copy each value to the matching setting.

    Next, run this command to generate a random 32 byte value and copy it to the `AUTH0_SECRET` field.

    ```bash generate random 32 byte value theme={null}
    openssl rand -hex 32
    ```

    ### Install frontend packages

    Ensure you have `npm` installed or follow the instructions here to [install npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm).
    Navigate to the `frontend` directory of your project and install the required packages:

    ```bash wrap lines theme={null}
    cd frontend
    npm install
    ```

    ### Run your application

    To run your application, start both the FastAPI backend and the frontend in two terminals:

    1. In one terminal, start the FastAPI backend:

    ```bash wrap lines theme={null}
    cd backend
    source .venv/bin/activate
    fastapi dev app/main.py
    ```

    2. In a second new terminal, start the frontend:

    ```bash wrap lines theme={null}
    cd frontend
    npm run dev
    ```

    Visit the URL `http://localhost:5173` in your browser.

    You will see:

    <Frame>
      <img
        src="https://mintlify.s3.us-west-1.amazonaws.com/auth0-genai/img/user_authentication_quickstart_login_screen.png"
        alt="Auth0 login
screen"
      />
    </Frame>

    Sign up to your application to create a new user account. You will then see a welcome message with your user name. You can sign in with that account on future visits.
  </Tab>
</Tabs>

## Next steps

* To set up first-party tool calling, complete the [Call your APIs on user's behalf](../get-started/call-your-apis-on-users-behalf) quickstart.
* To set up third-party tool calling, complete the [Call other's APIs on user's behalf](../get-started/call-others-apis-on-users-behalf) quickstart.
* Learn more about [User Authentication](/intro/user-authentication).
