# FusionAuth QuickStart for Rust Actix Web

Learn how to add FusionAuth login to a Rust Actix Web app.

> For the index of this section of the site, see [llms.txt](https://fusionauth.io/docs/llms.txt)

![Rust Actix Web](https://fusionauth.io/img/icons/rust.svg)

This QuickStart explains how to add a login page and authentication to a website built with [Actix Web](https://actix.rs/). You'll begin with a simple Actix Web app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.

This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.

## Prerequisites

This QuickStart requires:

*   [Rust](https://www.rust-lang.org/tools/install) 1.89 or later
*   [Docker](https://docs.docker.com/get-started/get-docker/) 23 or later

If you use macOS or Windows, you need one of the following container management tools:

*   [Docker Desktop](https://www.docker.com/products/docker-desktop/)
*   [OrbStack](https://docs.orbstack.dev/quick-start) (to use OrbStack for `docker compose` commands after installation, run `docker context use orbstack`)
*   [Podman](https://podman.io/docs/installation) (in the commands below, replace `docker` with `podman`)

## Create a Simple Actix Web App

For this QuickStart, we'll use an Actix Web app that reads and writes data to a text file:

1.  Create a Rust project for the app and navigate into it:
    
    ```shell-session
    $ cargo new rust-quickstart && cd rust-quickstart
    ```
    
    This creates a `Cargo.toml` file and a `src` folder with a `main.rs` file.
    
2.  Install dependencies:
    
    ```shell-session
    $ cargo add actix-web@4.20.0
    ```
    
    ```shell-session
    $ cargo add serde@1.0.229 --features derive
    ```
    
    [Actix Web](https://actix.rs/) is the web framework, and [Serde](https://serde.rs/) reads the submitted form into a Rust struct.
    
3.  Replace the contents of `src/main.rs` with the following code:
    
    ```rust
    use actix_web::{get, http::header, post, web, App, HttpResponse, HttpServer};
    use serde::Deserialize;
    use std::fs;
    
    const NOTE_PATH: &str = "note.txt";
    
    #[derive(Deserialize)]
    struct NoteForm {
        content: String,
    }
    
    fn escape(text: &str) -> String {
        text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
    }
    
    #[get("/")]
    async fn index() -> HttpResponse {
        let note = fs::read_to_string(NOTE_PATH).unwrap_or_default();
        HttpResponse::Ok().content_type("text/html; charset=utf-8").body(format!(
            r#"<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Notes</h1>
        <form method="post" action="/">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40">{}</textarea><br>
            <button type="submit">Save Changes</button>
        </form>
    </body>
    </html>"#,
            escape(&note)
        ))
    }
    
    #[post("/")]
    async fn save(form: web::Form<NoteForm>) -> std::io::Result<HttpResponse> {
        fs::write(NOTE_PATH, &form.content)?;
        Ok(HttpResponse::SeeOther()
            .insert_header((header::LOCATION, "/"))
            .finish())
    }
    
    #[actix_web::main]
    async fn main() -> std::io::Result<()> {
        HttpServer::new(|| App::new().service(index).service(save))
            .bind(("localhost", 3000))?
            .run()
            .await
    }
    ```
    
    The `index` handler reads the note when the page loads, and the `save` handler writes the note when the form is submitted. The `escape` function stops text in the note from being read as HTML.
    
4.  Run the app:
    
    ```shell-session
    $ cargo run
    ```
    
    The first build downloads and compiles the dependencies, which can take a few minutes.
    
5.  Open the app at [http://localhost:3000](http://localhost:3000).
    
6.  Type "Hello Rust" in the text area, then click Save Changes .
    
7.  In a file browser or terminal, look in the `rust-quickstart` folder. You should see a new file named `note.txt`, with text content "Hello Rust".
    
8.  Press **Ctrl+C** on your keyboard to stop the app.
    

## Install and Run FusionAuth

Before we can add authentication to our Actix Web app, we need a local FusionAuth instance:

1.  Open your container management tool (listed in the prerequisites above).
    
2.  From the `rust-quickstart` folder, clone the [GitHub repository for the FusionAuth instance you'll use with this QuickStart](https://github.com/FusionAuth/fusionauth-quickstart-app):
    
    ```shell-session
    $ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git
    ```
    
3.  Navigate into the cloned directory:
    
    ```shell-session
    $ cd fusionauth-quickstart-app
    ```
    
4.  To start a local instance of FusionAuth, run the following command (omit the `-d` flag to see all Docker logs):
    
    ```shell-session
    $ docker compose up -d
    ```
    
5.  Wait until all networks, volumes, and containers show a green status of **Healthy**, **Started**, or **Created**. This may take a few minutes, depending on your network speed and cached dependencies.
    
6.  Open [http://localhost:9011/admin](http://localhost:9011/admin) to access the FusionAuth Admin UI.
    
7.  Log in with these credentials:
    
    *   **Login**: `admin@example.com`
    *   **Password**: `password`
8.  Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the OAuth tab. On this page, you can find your client Id and client secret, and set redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our Actix Web app with FusionAuth.
    
9.  Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Actix Web app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.
    

## Add FusionAuth to the Actix Web App

Now that you have a working instance of FusionAuth and a working Actix Web app, let's use FusionAuth to add login to your Actix Web app:

1.  Navigate out of the `fusionauth-quickstart-app` folder, back to the `rust-quickstart` folder that contains `Cargo.toml` and `note.txt`:
    
    ```shell-session
    $ cd ..
    ```
    
2.  Install the dependencies we'll need to authenticate with FusionAuth:
    
    ```shell-session
    $ cargo add actix-session@0.12.0 --features cookie-session
    ```
    
    ```shell-session
    $ cargo add openidconnect@4.1.0
    ```
    
    [actix-session](https://docs.rs/actix-session/) keeps the user logged in with an encrypted session cookie, and [openidconnect](https://docs.rs/openidconnect/) handles communication with our FusionAuth instance.
    
3.  Replace the contents of `src/main.rs` with the following code:
    
    ```rust
    use actix_session::{storage::CookieSessionStore, Session, SessionMiddleware};
    use actix_web::{
        cookie::Key, error, get, http::header, post, web, App, HttpResponse, HttpServer,
    };
    use openidconnect::core::{CoreClient, CoreProviderMetadata, CoreResponseType};
    use openidconnect::{
        reqwest, url::Url, AuthenticationFlow, AuthorizationCode, ClientId, ClientSecret, CsrfToken,
        EndpointMaybeSet, EndpointNotSet, EndpointSet, IssuerUrl, Nonce, PkceCodeChallenge,
        PkceCodeVerifier, RedirectUrl,
    };
    use serde::Deserialize;
    use std::fs;
    
    const FUSIONAUTH_URL: &str = "http://localhost:9011";
    const CLIENT_ID: &str = "f0510a74-da7a-4101-a474-05e7f1d5ba7e";
    const CLIENT_SECRET: &str = "super-secret-secret-that-should-be-regenerated-for-production";
    const CALLBACK_URL: &str = "http://localhost:3000/oauth-callback";
    const LOGOUT_REDIRECT_URL: &str = "http://localhost:3000/login";
    const NOTE_PATH: &str = "note.txt";
    
    type FusionAuthClient =
        CoreClient<EndpointSet, EndpointNotSet, EndpointNotSet, EndpointNotSet, EndpointMaybeSet, EndpointMaybeSet>;
    
    struct AppState {
        client: FusionAuthClient,
        http: reqwest::Client,
    }
    
    #[derive(Deserialize)]
    struct NoteForm {
        content: String,
        csrf_token: String,
    }
    
    #[derive(Deserialize)]
    struct LogoutForm {
        csrf_token: String,
    }
    
    #[derive(Deserialize)]
    struct CallbackQuery {
        code: String,
        state: String,
    }
    
    fn escape(text: &str) -> String {
        text.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
            .replace('"', "&quot;")
    }
    
    fn redirect(location: &str) -> HttpResponse {
        HttpResponse::SeeOther()
            .insert_header((header::LOCATION, location))
            .finish()
    }
    
    fn html(body: String) -> HttpResponse {
        HttpResponse::Ok().content_type("text/html; charset=utf-8").body(body)
    }
    
    fn check_csrf(session: &Session, token: &str) -> actix_web::Result<()> {
        match session.get::<String>("csrf_token")? {
            Some(expected) if expected == token => Ok(()),
            _ => Err(error::ErrorBadRequest("Invalid CSRF token")),
        }
    }
    
    #[get("/login")]
    async fn login_page() -> HttpResponse {
        html(r#"<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Log in</title>
    </head>
    <body>
        <h1>Log in to Notes</h1>
        <a href="/login/start">Log in with FusionAuth</a>
    </body>
    </html>"#
            .to_string())
    }
    
    #[get("/login/start")]
    async fn login_start(state: web::Data<AppState>, session: Session) -> actix_web::Result<HttpResponse> {
        let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
        let (auth_url, csrf_state, nonce) = state
            .client
            .authorize_url(
                AuthenticationFlow::<CoreResponseType>::AuthorizationCode,
                CsrfToken::new_random,
                Nonce::new_random,
            )
            .set_pkce_challenge(pkce_challenge)
            .url();
    
        session.insert("oauth_state", csrf_state.secret())?;
        session.insert("nonce", nonce.secret())?;
        session.insert("pkce_verifier", pkce_verifier.secret())?;
        Ok(redirect(auth_url.as_str()))
    }
    
    #[get("/oauth-callback")]
    async fn oauth_callback(
        state: web::Data<AppState>,
        session: Session,
        query: web::Query<CallbackQuery>,
    ) -> actix_web::Result<HttpResponse> {
        let (Some(expected_state), Some(nonce), Some(pkce_verifier)) = (
            session.remove_as::<String>("oauth_state").and_then(Result::ok),
            session.remove_as::<String>("nonce").and_then(Result::ok),
            session.remove_as::<String>("pkce_verifier").and_then(Result::ok),
        ) else {
            return Ok(redirect("/login"));
        };
        if query.state != expected_state {
            return Err(error::ErrorBadRequest("Invalid state"));
        }
    
        let token_response = state
            .client
            .exchange_code(AuthorizationCode::new(query.code.clone()))
            .map_err(error::ErrorInternalServerError)?
            .set_pkce_verifier(PkceCodeVerifier::new(pkce_verifier))
            .request_async(&state.http)
            .await
            .map_err(error::ErrorUnauthorized)?;
    
        let id_token = token_response
            .extra_fields()
            .id_token()
            .ok_or_else(|| error::ErrorUnauthorized("No ID token in response"))?;
        let claims = id_token
            .claims(&state.client.id_token_verifier(), &Nonce::new(nonce))
            .map_err(error::ErrorUnauthorized)?;
    
        session.renew();
        session.insert("user_id", claims.subject().as_str())?;
        session.insert("csrf_token", CsrfToken::new_random().secret())?;
        Ok(redirect("/"))
    }
    
    #[get("/")]
    async fn index(session: Session) -> actix_web::Result<HttpResponse> {
        if session.get::<String>("user_id")?.is_none() {
            return Ok(redirect("/login"));
        }
        let csrf_token = session.get::<String>("csrf_token")?.unwrap_or_default();
        let note = fs::read_to_string(NOTE_PATH).unwrap_or_default();
        Ok(html(format!(
            r#"<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Notes</h1>
        <form method="post" action="/">
            <input type="hidden" name="csrf_token" value="{csrf_token}">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40">{note}</textarea><br>
            <button type="submit">Save Changes</button>
        </form>
        <form method="post" action="/logout">
            <input type="hidden" name="csrf_token" value="{csrf_token}">
            <button type="submit">Logout</button>
        </form>
    </body>
    </html>"#,
            csrf_token = escape(&csrf_token),
            note = escape(&note),
        )))
    }
    
    #[post("/")]
    async fn save(session: Session, form: web::Form<NoteForm>) -> actix_web::Result<HttpResponse> {
        if session.get::<String>("user_id")?.is_none() {
            return Ok(redirect("/login"));
        }
        check_csrf(&session, &form.csrf_token)?;
        fs::write(NOTE_PATH, &form.content)?;
        Ok(redirect("/"))
    }
    
    #[post("/logout")]
    async fn logout(session: Session, form: web::Form<LogoutForm>) -> actix_web::Result<HttpResponse> {
        check_csrf(&session, &form.csrf_token)?;
        session.purge();
        let logout_url = Url::parse_with_params(
            &format!("{FUSIONAUTH_URL}/oauth2/logout"),
            &[("client_id", CLIENT_ID), ("post_logout_redirect_uri", LOGOUT_REDIRECT_URL)],
        )
        .map_err(error::ErrorInternalServerError)?;
        Ok(redirect(logout_url.as_str()))
    }
    
    #[actix_web::main]
    async fn main() -> std::io::Result<()> {
        let http = reqwest::ClientBuilder::new()
            // prevents SSRF through redirects, as recommended by the openidconnect crate
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .expect("Failed to build HTTP client");
        let metadata = CoreProviderMetadata::discover_async(
            IssuerUrl::new(FUSIONAUTH_URL.to_string()).unwrap(),
            &http,
        )
        .await
        .expect("Failed to read FusionAuth's OpenID Connect configuration");
        let client = CoreClient::from_provider_metadata(
            metadata,
            ClientId::new(CLIENT_ID.to_string()),
            Some(ClientSecret::new(CLIENT_SECRET.to_string())),
        )
        .set_redirect_uri(RedirectUrl::new(CALLBACK_URL.to_string()).unwrap());
    
        let state = web::Data::new(AppState { client, http });
        let key = Key::generate();
        HttpServer::new(move || {
            App::new()
                .app_data(state.clone())
                .wrap(
                    SessionMiddleware::builder(CookieSessionStore::default(), key.clone())
                        // the app runs on plain HTTP during development
                        .cookie_secure(false)
                        .build(),
                )
                .service(login_page)
                .service(login_start)
                .service(oauth_callback)
                .service(index)
                .service(save)
                .service(logout)
        })
        .bind(("localhost", 3000))?
        .run()
        .await
    }
    ```
    
    The new code connects the app to FusionAuth:
    
    *   The constants at the top of the file hold the client Id, client secret, and redirect URLs (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI).
    *   In `main`, `discover_async` reads FusionAuth's OpenID Connect discovery document at `/.well-known/openid-configuration` to find the login and token endpoints and the keys that sign tokens. `from_provider_metadata` creates the client the app uses to talk to FusionAuth.
    *   `SessionMiddleware` stores the session in a cookie that a key encrypts. The app generates a new key each time it starts, so restarting the app logs everyone out.
    *   The `index` and `save` handlers send users who aren't logged in to `/login`, which shows a Log in with FusionAuth link.
    *   The `/login/start` route sends the user to the FusionAuth login page. The route creates a [PKCE](https://fusionauth.io/docs/authentication/oauth/authorization-code.md#proof-key-for-code-exchange) code challenge, a state value, and a nonce, and saves the matching secrets in the session.
    *   The `/oauth-callback` route checks the state value, then exchanges the authorization code from FusionAuth for tokens, sending the PKCE code verifier with the request. The route validates the [ID token](https://fusionauth.io/docs/authentication/oauth/tokens.md#id-token) signature and nonce, then stores the user's Id in the session.
    *   After login, the app saves a random CSRF token in the session and adds the token to each form as a hidden field. The `check_csrf` function rejects a form submission whose token doesn't match, which prevents [CSRF](https://fusionauth.io/docs/apis/oauth/authorize.md).
    *   The `/logout` route clears the session, then sends the user to FusionAuth's `/oauth2/logout` endpoint so the FusionAuth session ends too. FusionAuth then sends the user back to the login page.
4.  Run the app, which now uses FusionAuth login:
    
    ```shell-session
    $ cargo run
    ```
    
5.  Open the app at [http://localhost:3000](http://localhost:3000) and click Log in with FusionAuth .
    
6.  Log in with the following credentials:
    
    *   **Login**: `richard@example.com`
    *   **Password**: `password`
7.  Edit and save the note in the authenticated Actix Web app.
    
8.  Click Logout . FusionAuth ends your session and sends you back to the login page.
    
9.  Press **Ctrl+C** on your keyboard to stop the app.
    

## Add Independent Notes for Each User

To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:

1.  Open the FusionAuth Admin UI at [http://localhost:9011/admin](http://localhost:9011/admin).
    
2.  Log in with the following credentials:
    
    *   **Login**: `admin@example.com`
    *   **Password**: `password`
3.  Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the Registration tab.
    
    *   Under **Self-service registration**, check that **Registration mode** is set to **Create registration**. The QuickStart configuration has already turned on self-service registration.
    *   In the **Registration field** list, turn on the **Enabled** and **Required** switches for the following rows:
        *   **Birthdate**
        *   **First name**
        *   **Last name**
4.  Click Save in the top right of the page to save your changes to self-service registration.
    
5.  Navigate to Users . In the Richard Hendricks row, click Select -> Manage .
    
6.  In the Source tab, look for the `firstName` and `lastName` fields. That's what we'll use to personalize the UI for each user. We'll use the user's `id` field to generate a unique name for each user's note.
    
7.  Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Actix Web app.
    
8.  Replace the contents of `src/main.rs` with the following code:
    
    ```rust
    use actix_session::{storage::CookieSessionStore, Session, SessionMiddleware};
    use actix_web::{
        cookie::Key, error, get, http::header, post, web, App, HttpResponse, HttpServer,
    };
    use openidconnect::core::{CoreClient, CoreProviderMetadata, CoreResponseType};
    use openidconnect::{
        reqwest, url::Url, AuthenticationFlow, AuthorizationCode, ClientId, ClientSecret, CsrfToken,
        EndpointMaybeSet, EndpointNotSet, EndpointSet, IssuerUrl, Nonce, PkceCodeChallenge,
        PkceCodeVerifier, RedirectUrl, Scope,
    };
    use serde::Deserialize;
    use std::fs;
    use std::path::PathBuf;
    
    const FUSIONAUTH_URL: &str = "http://localhost:9011";
    const CLIENT_ID: &str = "f0510a74-da7a-4101-a474-05e7f1d5ba7e";
    const CLIENT_SECRET: &str = "super-secret-secret-that-should-be-regenerated-for-production";
    const CALLBACK_URL: &str = "http://localhost:3000/oauth-callback";
    const LOGOUT_REDIRECT_URL: &str = "http://localhost:3000/login";
    
    type FusionAuthClient =
        CoreClient<EndpointSet, EndpointNotSet, EndpointNotSet, EndpointNotSet, EndpointMaybeSet, EndpointMaybeSet>;
    
    struct AppState {
        client: FusionAuthClient,
        http: reqwest::Client,
    }
    
    #[derive(Deserialize)]
    struct NoteForm {
        content: String,
        csrf_token: String,
    }
    
    #[derive(Deserialize)]
    struct LogoutForm {
        csrf_token: String,
    }
    
    #[derive(Deserialize)]
    struct CallbackQuery {
        code: String,
        state: String,
    }
    
    fn escape(text: &str) -> String {
        text.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
            .replace('"', "&quot;")
    }
    
    fn note_path(user_id: &str) -> PathBuf {
        PathBuf::from("user_data").join(format!("note-{user_id}.txt"))
    }
    
    fn redirect(location: &str) -> HttpResponse {
        HttpResponse::SeeOther()
            .insert_header((header::LOCATION, location))
            .finish()
    }
    
    fn html(body: String) -> HttpResponse {
        HttpResponse::Ok().content_type("text/html; charset=utf-8").body(body)
    }
    
    fn check_csrf(session: &Session, token: &str) -> actix_web::Result<()> {
        match session.get::<String>("csrf_token")? {
            Some(expected) if expected == token => Ok(()),
            _ => Err(error::ErrorBadRequest("Invalid CSRF token")),
        }
    }
    
    #[get("/login")]
    async fn login_page() -> HttpResponse {
        html(r#"<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Log in</title>
    </head>
    <body>
        <h1>Log in to Notes</h1>
        <a href="/login/start">Log in with FusionAuth</a>
    </body>
    </html>"#
            .to_string())
    }
    
    #[get("/login/start")]
    async fn login_start(state: web::Data<AppState>, session: Session) -> actix_web::Result<HttpResponse> {
        let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
        let (auth_url, csrf_state, nonce) = state
            .client
            .authorize_url(
                AuthenticationFlow::<CoreResponseType>::AuthorizationCode,
                CsrfToken::new_random,
                Nonce::new_random,
            )
            .add_scope(Scope::new("profile".to_string()))
            .set_pkce_challenge(pkce_challenge)
            .url();
    
        session.insert("oauth_state", csrf_state.secret())?;
        session.insert("nonce", nonce.secret())?;
        session.insert("pkce_verifier", pkce_verifier.secret())?;
        Ok(redirect(auth_url.as_str()))
    }
    
    #[get("/oauth-callback")]
    async fn oauth_callback(
        state: web::Data<AppState>,
        session: Session,
        query: web::Query<CallbackQuery>,
    ) -> actix_web::Result<HttpResponse> {
        let (Some(expected_state), Some(nonce), Some(pkce_verifier)) = (
            session.remove_as::<String>("oauth_state").and_then(Result::ok),
            session.remove_as::<String>("nonce").and_then(Result::ok),
            session.remove_as::<String>("pkce_verifier").and_then(Result::ok),
        ) else {
            return Ok(redirect("/login"));
        };
        if query.state != expected_state {
            return Err(error::ErrorBadRequest("Invalid state"));
        }
    
        let token_response = state
            .client
            .exchange_code(AuthorizationCode::new(query.code.clone()))
            .map_err(error::ErrorInternalServerError)?
            .set_pkce_verifier(PkceCodeVerifier::new(pkce_verifier))
            .request_async(&state.http)
            .await
            .map_err(error::ErrorUnauthorized)?;
    
        let id_token = token_response
            .extra_fields()
            .id_token()
            .ok_or_else(|| error::ErrorUnauthorized("No ID token in response"))?;
        let claims = id_token
            .claims(&state.client.id_token_verifier(), &Nonce::new(nonce))
            .map_err(error::ErrorUnauthorized)?;
    
        session.renew();
        let first_name = claims.given_name().and_then(|name| name.get(None));
        let last_name = claims.family_name().and_then(|name| name.get(None));
        let name = format!(
            "{} {}",
            first_name.map(|name| name.as_str()).unwrap_or_default(),
            last_name.map(|name| name.as_str()).unwrap_or_default()
        );
        let name = if name.trim().is_empty() { "writer" } else { name.trim() };
    
        session.insert("user_id", claims.subject().as_str())?;
        session.insert("name", name)?;
        session.insert("csrf_token", CsrfToken::new_random().secret())?;
        Ok(redirect("/"))
    }
    
    #[get("/")]
    async fn index(session: Session) -> actix_web::Result<HttpResponse> {
        let Some(user_id) = session.get::<String>("user_id")? else {
            return Ok(redirect("/login"));
        };
        let name = session.get::<String>("name")?.unwrap_or_default();
        let csrf_token = session.get::<String>("csrf_token")?.unwrap_or_default();
        let note = fs::read_to_string(note_path(&user_id))
            .unwrap_or_else(|_| format!("Write a note, {name}."));
        Ok(html(format!(
            r#"<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Welcome, {name}</h1>
        <form method="post" action="/">
            <input type="hidden" name="csrf_token" value="{csrf_token}">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40">{note}</textarea><br>
            <button type="submit">Save Changes</button>
        </form>
        <form method="post" action="/logout">
            <input type="hidden" name="csrf_token" value="{csrf_token}">
            <button type="submit">Logout</button>
        </form>
    </body>
    </html>"#,
            csrf_token = escape(&csrf_token),
            name = escape(&name),
            note = escape(&note),
        )))
    }
    
    #[post("/")]
    async fn save(session: Session, form: web::Form<NoteForm>) -> actix_web::Result<HttpResponse> {
        let Some(user_id) = session.get::<String>("user_id")? else {
            return Ok(redirect("/login"));
        };
        check_csrf(&session, &form.csrf_token)?;
        fs::create_dir_all("user_data")?;
        fs::write(note_path(&user_id), &form.content)?;
        Ok(redirect("/"))
    }
    
    #[post("/logout")]
    async fn logout(session: Session, form: web::Form<LogoutForm>) -> actix_web::Result<HttpResponse> {
        check_csrf(&session, &form.csrf_token)?;
        session.purge();
        let logout_url = Url::parse_with_params(
            &format!("{FUSIONAUTH_URL}/oauth2/logout"),
            &[("client_id", CLIENT_ID), ("post_logout_redirect_uri", LOGOUT_REDIRECT_URL)],
        )
        .map_err(error::ErrorInternalServerError)?;
        Ok(redirect(logout_url.as_str()))
    }
    
    #[actix_web::main]
    async fn main() -> std::io::Result<()> {
        let http = reqwest::ClientBuilder::new()
            // prevents SSRF through redirects, as recommended by the openidconnect crate
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .expect("Failed to build HTTP client");
        let metadata = CoreProviderMetadata::discover_async(
            IssuerUrl::new(FUSIONAUTH_URL.to_string()).unwrap(),
            &http,
        )
        .await
        .expect("Failed to read FusionAuth's OpenID Connect configuration");
        let client = CoreClient::from_provider_metadata(
            metadata,
            ClientId::new(CLIENT_ID.to_string()),
            Some(ClientSecret::new(CLIENT_SECRET.to_string())),
        )
        .set_redirect_uri(RedirectUrl::new(CALLBACK_URL.to_string()).unwrap());
    
        let state = web::Data::new(AppState { client, http });
        let key = Key::generate();
        HttpServer::new(move || {
            App::new()
                .app_data(state.clone())
                .wrap(
                    SessionMiddleware::builder(CookieSessionStore::default(), key.clone())
                        // the app runs on plain HTTP during development
                        .cookie_secure(false)
                        .build(),
                )
                .service(login_page)
                .service(login_start)
                .service(oauth_callback)
                .service(index)
                .service(save)
                .service(logout)
        })
        .bind(("localhost", 3000))?
        .run()
        .await
    }
    ```
    
    The app now requests the `profile` scope, so the ID token includes the user's first and last name. After validating the ID token, the `/oauth-callback` route stores the user's name and Id in the session. The `index` and `save` handlers use the Id to read and write a separate note file for each user in the `user_data` folder, and the page greets the user by name.
    
9.  Run the app:
    
    ```shell-session
    $ cargo run
    ```
    
10.  Open the app at [http://localhost:3000](http://localhost:3000) and click Log in with FusionAuth .
     
11.  Log in with the following credentials:
     
     *   **Login**: `richard@example.com`
     *   **Password**: `password`
12.  In a separate private or incognito window, open the app at [http://localhost:3000](http://localhost:3000) and click Log in with FusionAuth .
     
13.  Click Create an account and create an account using your personal email address, a password, your name, and your birthdate.
     
14.  Edit and save your own note. Your name appears at the top of the page and in the default note text.
     

Your Actix Web app now provides unique notes for each user. Each user can independently edit and save their note. When a user saves a note, the app writes the note to a `note-<id>.txt` file in the `user_data` directory. To identify which note belongs to which user, compare the `id` in the file name with the `id` field in the user's Source tab in the Admin UI. Log out of the app before you open the Admin UI. Otherwise, FusionAuth single sign-on logs you in to the Admin UI as the app user, who doesn't have access to the Admin UI.

## Summary

In this QuickStart, FusionAuth handled login for your Actix Web app:

*   The openidconnect crate sent users to the FusionAuth login page and exchanged the authorization code for tokens, so the app never saw their passwords.
*   The session check in each handler kept logged-out users away from the notes page.
*   The ID token gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
*   FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.

## Next Steps

This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see [Get Started](https://fusionauth.io/docs/get-started.md).

FusionAuth has many features (including [Social Login](https://fusionauth.io/docs/authentication/identity-providers.md#social-identity-providers), [Single Sign-On](https://fusionauth.io/docs/authentication/sessions/enable-sso.md), [Passkeys](https://fusionauth.io/docs/authentication/passkeys/configure.md), [Multi-factor Authentication](https://fusionauth.io/docs/authentication/multi-factor-authentication.md)), most of which are free. This example app is a great starting point for learning about FusionAuth features.
---

## Other pages in Web

> For the full index of this section, see [Quickstarts](https://fusionauth.io/docs/llms-quickstarts.txt).

- [FusionAuth QuickStart for Python Django](https://fusionauth.io/docs/quickstarts/web/django.md): Integrate FusionAuth with an example Python Django website.
- [FusionAuth QuickStart for .NET](https://fusionauth.io/docs/quickstarts/web/dotnet.md): Learn how to add FusionAuth login to an ASP.NET Core Razor Pages app.
- [FusionAuth QuickStart for Express](https://fusionauth.io/docs/quickstarts/web/express.md): Integrate FusionAuth with an example Express website.
- [FusionAuth QuickStart for Python Flask](https://fusionauth.io/docs/quickstarts/web/flask.md): Integrate FusionAuth with an example Python Flask website.
- [FusionAuth QuickStart for Go](https://fusionauth.io/docs/quickstarts/web/go.md): Learn how to add FusionAuth login to a Go web app built with the standard library.
- [Web](https://fusionauth.io/docs/quickstarts/web.md): Explore step-by-step web application QuickStart guides from FusionAuth to seamlessly integrate authentication into your application.
- [FusionAuth QuickStart for Laravel](https://fusionauth.io/docs/quickstarts/web/laravel.md): Learn how to add FusionAuth login to a PHP Laravel app.
- [FusionAuth QuickStart for Next.js](https://fusionauth.io/docs/quickstarts/web/nextjs.md): Integrate FusionAuth with an example Next.js website.
- [FusionAuth QuickStart for Nuxt](https://fusionauth.io/docs/quickstarts/web/nuxt.md): Integrate FusionAuth with an example Nuxt website.
- [FusionAuth QuickStart for PHP](https://fusionauth.io/docs/quickstarts/web/php.md): Learn how to add FusionAuth login to a plain PHP app.
- [FusionAuth QuickStart for Drupal](https://fusionauth.io/docs/quickstarts/web/quickstart-php-drupal-web.md): QuickStart integration of Drupal web application with FusionAuth.
- [FusionAuth QuickStart for WordPress](https://fusionauth.io/docs/quickstarts/web/quickstart-wordpress-web.md): QuickStart integration of WordPress application with FusionAuth.
- [FusionAuth QuickStart for Ruby on Rails](https://fusionauth.io/docs/quickstarts/web/rails.md): Integrate FusionAuth with an example Ruby on Rails website.
- [FusionAuth QuickStart for React Router](https://fusionauth.io/docs/quickstarts/web/react-router.md): Learn how to add FusionAuth login to a React Router app.
- [FusionAuth QuickStart for Remix](https://fusionauth.io/docs/quickstarts/web/remix.md): Learn how to add FusionAuth login to a Remix app.
- [FusionAuth QuickStart for Spring Boot With Thymeleaf](https://fusionauth.io/docs/quickstarts/web/spring-boot.md): Learn how to add FusionAuth login to a Spring Boot app with Thymeleaf.
