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

# Authentification des utilisateurs

> Utilisez la connexion universelle d’Auth0 pour permettre aux agents d’IA d’authentifier les utilisateurs en toute sécurité.

L’authentification est le processus qui consiste à prouver l’identité d’un utilisateur avant de lui accorder l’accès à une ressource. Dans ce démarrage rapide, vous apprendrez à intégrer la [connexion universelle](/docs/fr-ca/authenticate/login/auth0-universal-login) à votre agent d’IA et à tirer parti d’OAuth 2.0 et d’OpenID Connect pour authentifier les utilisateurs de façon sécurisée.

Lorsqu’un utilisateur s’authentifie auprès d’un fournisseur d’identité par l’intermédiaire d’Auth0, Auth0 peut transmettre les informations de l’utilisateur dans un jeton d’ID à une application ou à un agent d’IA afin d’offrir une expérience personnalisée. Par exemple, un robot conversationnel peut saluer un utilisateur par son nom et afficher des informations pertinentes selon son profil.

À la fin de ce démarrage rapide, vous devriez disposer d’une application capable de :

* S’inscrire et se connecter à l’aide d’un nom d’utilisateur et d’un mot de passe ou d’un compte Google.
* Authentifier et autoriser les utilisateurs à l’aide d’OAuth 2.0 et d’OpenID Connect.

## Choisissez votre pile technologique

**Next.js**

Prerequisites

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

**Use sample app (recommended)**

### Download sample app

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

Download authenticate-users vercel-ai-next-js sample code

### 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 **Applications > Applications ** 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:

![Auth0 login screen](https://mintlify.s3.us-west-1.amazonaws.com/auth0/docs/images/ai/user_authentication_quickstart_login_screen.png)

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.

**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:

![Auth0 login screen](https://mintlify.s3.us-west-1.amazonaws.com/auth0/docs/images/ai/user_authentication_quickstart_login_screen.png)

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).

**FastAPI**

Prerequisites

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

### Download sample app

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

Download authenticate-users langchain-fastapi-py sample code

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:

![Auth0 login
screen](https://mintlify.s3.us-west-1.amazonaws.com/auth0/docs/images/ai/user_authentication_quickstart_login_screen.png)

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.

## Prochaines étapes

* Pour configurer l'appel d'outils internes, suivez le guide de démarrage rapide [Appeler des API internes au nom de l'utilisateur](./call-first-party-apis-on-users-behalf).
* Pour configurer l'appel d'outils tiers, suivez le guide de démarrage rapide [Appeler des API tierces au nom de l'utilisateur](./call-third-party-apis-on-users-behalf).
* Pour en savoir plus, consultez la page [Authentification des utilisateurs](/ai/docs/fr-ca/intro/user-authentication).
