# FusionAuth QuickStart for Spring Boot With Thymeleaf

Learn how to add FusionAuth login to a Spring Boot app with Thymeleaf.

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

![Spring Boot With Thymeleaf](https://fusionauth.io/img/icons/spring.svg)

This QuickStart explains how to add a login page and authentication to a website built with [Spring Boot](https://spring.io/projects/spring-boot) and [Thymeleaf](https://www.thymeleaf.org/). You'll begin with a simple Spring Boot 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:

*   [Java JDK](https://adoptium.net/temurin/releases/?version=21) 21 or later
*   [Maven](https://maven.apache.org/install.html) 3.9 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 Spring Boot App

For this QuickStart, we'll use a Spring Boot app that reads and writes data to a text file:

1.  Create a folder for the app and navigate into it:
    
    ```shell-session
    $ mkdir spring-boot-quickstart && cd spring-boot-quickstart
    ```
    
2.  Create folders for the app's Java code and templates:
    
    ```shell-session
    $ mkdir -p src/main/java/example/notes src/main/resources/templates
    ```
    
3.  Create a file named `pom.xml` with the following contents, which adds Spring MVC and Thymeleaf:
    
    ```xml
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>4.1.3</version>
        </parent>
        <groupId>example</groupId>
        <artifactId>notes</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <properties>
            <java.version>21</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-webmvc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>
    ```
    
4.  Create a file named `src/main/java/example/notes/NotesApplication.java` with the following code, which starts the app:
    
    ```java
    package example.notes;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class NotesApplication {
        public static void main(String[] args) {
            SpringApplication.run(NotesApplication.class, args);
        }
    }
    ```
    
5.  Create a file named `src/main/java/example/notes/NotesController.java` with the following code:
    
    ```java
    package example.notes;
    
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @Controller
    public class NotesController {
        private static final Path NOTE = Path.of("note.txt");
    
        @GetMapping("/")
        String show(Model model) throws IOException {
            model.addAttribute("content", Files.exists(NOTE) ? Files.readString(NOTE) : "");
            return "notes";
        }
    
        @PostMapping("/")
        String save(@RequestParam String content) throws IOException {
            Files.writeString(NOTE, content);
            return "redirect:/";
        }
    }
    ```
    
    The `show` method reads the note when the page loads, and the `save` method saves it when the form is submitted.
    
6.  Create a file named `src/main/resources/templates/notes.html` with the following code, which displays the note in a form:
    
    ```html
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Notes</h1>
        <form method="post" th:action="@{/}">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40" th:text="${content}"></textarea><br>
            <button type="submit">Save Changes</button>
        </form>
    </body>
    </html>
    ```
    
7.  Run the app:
    
    ```shell-session
    $ mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=3000
    ```
    
8.  Open the app at [http://localhost:3000](http://localhost:3000).
    
9.  Type "Hello Spring Boot" in the text area, then click Save Changes .
    
10.  In a file browser or terminal, look in the `spring-boot-quickstart` folder. You should see a new file named `note.txt`, with text content "Hello Spring Boot".
     
11.  Press **Ctrl+C** on your keyboard to stop the app.
     

## Install and Run FusionAuth

Before we can add authentication to our Spring Boot app, we need a local FusionAuth instance:

1.  Open your container management tool (listed in the prerequisites above).
    
2.  From the `spring-boot-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:
    
    *   username: `admin@example.com`
    *   password: `password`
8.  Navigate to Applications -> QuickStart App -> Edit -> OAuth . 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 Spring Boot 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 Spring Boot 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 Spring Boot App

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

1.  Navigate out of the `fusionauth-quickstart-app` folder, back to the `spring-boot-quickstart` folder that contains `pom.xml` and `note.txt`:
    
    ```shell-session
    $ cd ..
    ```
    
2.  Replace the contents of `pom.xml` with the following code, which adds the Spring Security OAuth2 client. This handles communication with our FusionAuth instance:
    
    ```xml
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>4.1.3</version>
        </parent>
        <groupId>example</groupId>
        <artifactId>notes</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <properties>
            <java.version>21</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-webmvc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security-oauth2-client</artifactId>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>
    ```
    
3.  Create a file named `src/main/resources/application.properties` with the following contents (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):
    
    ```properties
    spring.security.oauth2.client.provider.fusionauth.issuer-uri=http://localhost:9011
    
    spring.security.oauth2.client.registration.fusionauth.client-id=f0510a74-da7a-4101-a474-05e7f1d5ba7e
    spring.security.oauth2.client.registration.fusionauth.client-secret=super-secret-secret-that-should-be-regenerated-for-production
    spring.security.oauth2.client.registration.fusionauth.authorization-grant-type=authorization_code
    spring.security.oauth2.client.registration.fusionauth.redirect-uri={baseUrl}/oauth-callback
    spring.security.oauth2.client.registration.fusionauth.scope=openid
    ```
    
    Spring Security finds the login and token endpoints in the OpenID Connect discovery document for the `issuer-uri`.
    
4.  Create a file named `src/main/java/example/notes/SecurityConfig.java` with the following code:
    
    ```java
    package example.notes;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
    import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
    import org.springframework.security.web.SecurityFilterChain;
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class SecurityConfig implements WebMvcConfigurer {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/login").setViewName("login");
        }
    
        @Bean
        SecurityFilterChain security(HttpSecurity http, ClientRegistrationRepository clients) throws Exception {
            var logoutHandler = new OidcClientInitiatedLogoutSuccessHandler(clients);
            logoutHandler.setPostLogoutRedirectUri("{baseUrl}/login");
    
            return http
                .authorizeHttpRequests(routes -> routes
                    .requestMatchers("/login").permitAll()
                    .anyRequest().authenticated())
                .oauth2Login(login -> login
                    .loginPage("/login")
                    .redirectionEndpoint(callback -> callback.baseUri("/oauth-callback")))
                .logout(logout -> logout.logoutSuccessHandler(logoutHandler))
                .build();
        }
    }
    ```
    
    The new code connects the app to FusionAuth:
    
    *   `addViewControllers` shows the `login.html` template at `/login`.
    *   `authorizeHttpRequests` lets anyone open `/login`, and sends users who aren't logged in to `/login` for every other route.
    *   `oauth2Login` sets `/oauth-callback` as the route that receives the authorization code from FusionAuth. Spring Security exchanges the code for tokens, using [PKCE](https://fusionauth.io/docs/authentication/oauth/authorization-code.md#proof-key-for-code-exchange), and validates the [ID token](https://fusionauth.io/docs/authentication/oauth/tokens.md#id-token).
    *   The `OidcClientInitiatedLogoutSuccessHandler` sends the user to FusionAuth's logout endpoint so the FusionAuth session ends too, then back to the login page.
5.  Create a file named `src/main/resources/templates/login.html` with the following code:
    
    ```html
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="utf-8">
        <title>Log in</title>
    </head>
    <body>
        <h1>Log in to Notes</h1>
        <a th:href="@{/oauth2/authorization/fusionauth}">Log in with FusionAuth</a>
    </body>
    </html>
    ```
    
    The link opens `/oauth2/authorization/fusionauth`, which sends the user to the FusionAuth login page using the `fusionauth` client registration in `application.properties`.
    
6.  Replace the contents of `src/main/resources/templates/notes.html` with the following code, which adds a Logout button:
    
    ```html
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Notes</h1>
        <form method="post" th:action="@{/}">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40" th:text="${content}"></textarea><br>
            <button type="submit">Save Changes</button>
        </form>
        <form method="post" th:action="@{/logout}">
            <button type="submit">Logout</button>
        </form>
    </body>
    </html>
    ```
    
    The `th:action` attributes add the [CSRF](https://fusionauth.io/docs/apis/oauth/authorize.md) token Spring Security requires for both forms.
    
7.  Run the app, which now uses FusionAuth login:
    
    ```shell-session
    $ mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=3000
    ```
    
8.  Open the app at [http://localhost:3000](http://localhost:3000) and click Log in with FusionAuth .
    
9.  Log in with the following credentials:
    
    *   username: `richard@example.com`
    *   password: `password`
10.  Edit and save the note in the authenticated Spring Boot app.
     
11.  Click Logout . FusionAuth ends your session and sends you back to the login page.
     
12.  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:
    
    *   username: `admin@example.com`
    *   password: `password`
3.  Navigate to Applications -> QuickStart App -> Edit -> Registration .
    
    *   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 -> Richard Hendricks -> 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 Spring Boot app.
    
8.  Replace the contents of `src/main/resources/application.properties` with the following contents, which add the `profile` scope so the ID token includes the user's first and last name:
    
    ```properties
    spring.security.oauth2.client.provider.fusionauth.issuer-uri=http://localhost:9011
    
    spring.security.oauth2.client.registration.fusionauth.client-id=f0510a74-da7a-4101-a474-05e7f1d5ba7e
    spring.security.oauth2.client.registration.fusionauth.client-secret=super-secret-secret-that-should-be-regenerated-for-production
    spring.security.oauth2.client.registration.fusionauth.authorization-grant-type=authorization_code
    spring.security.oauth2.client.registration.fusionauth.redirect-uri={baseUrl}/oauth-callback
    spring.security.oauth2.client.registration.fusionauth.scope=openid,profile
    ```
    
9.  Replace the contents of `src/main/java/example/notes/NotesController.java` with the following code, which reads the user's name (first and last) and Id from the ID token, and stores each user's note in a separate file:
    
    ```java
    package example.notes;
    
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.util.Objects;
    import java.util.UUID;
    
    import org.springframework.security.core.annotation.AuthenticationPrincipal;
    import org.springframework.security.oauth2.core.oidc.user.OidcUser;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @Controller
    public class NotesController {
        private static final Path NOTES = Path.of("user_data");
    
        @GetMapping("/")
        String show(@AuthenticationPrincipal OidcUser user, Model model) throws IOException {
            Path note = notePath(user);
            String firstName = Objects.toString(user.getGivenName(), "");
            String lastName = Objects.toString(user.getFamilyName(), "");
            String fullName = (firstName + " " + lastName).strip();
            String name = fullName.isEmpty() ? "writer" : fullName;
            model.addAttribute("name", name);
            model.addAttribute("content", Files.exists(note) ? Files.readString(note) : "Write a note, " + name + ".");
            return "notes";
        }
    
        @PostMapping("/")
        String save(@AuthenticationPrincipal OidcUser user, @RequestParam String content) throws IOException {
            Files.createDirectories(NOTES);
            Files.writeString(notePath(user), content);
            return "redirect:/";
        }
    
        private Path notePath(OidcUser user) {
            UUID userId = UUID.fromString(user.getSubject());
            return NOTES.resolve("note-" + userId + ".txt");
        }
    }
    ```
    
    Spring Security validated the ID token at login and passes its claims to each method as an `OidcUser`, so we don't need a separate JWT library.
    
10.  Replace the contents of `src/main/resources/templates/notes.html` with the following code, which greets the user by name:
     
     ```html
     <!DOCTYPE html>
     <html lang="en" xmlns:th="http://www.thymeleaf.org">
     <head>
         <meta charset="utf-8">
         <title>Notes</title>
     </head>
     <body>
         <h1 th:text="|Welcome, ${name}|">Notes</h1>
         <form method="post" th:action="@{/}">
             <label for="content">Your note</label><br>
             <textarea id="content" name="content" rows="8" cols="40" th:text="${content}"></textarea><br>
             <button type="submit">Save Changes</button>
         </form>
         <form method="post" th:action="@{/logout}">
             <button type="submit">Logout</button>
         </form>
     </body>
     </html>
     ```
     
11.  Run the app:
     
     ```shell-session
     $ mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=3000
     ```
     
12.  Open the app at [http://localhost:3000](http://localhost:3000) and click Log in with FusionAuth .
     
13.  Log in with the following credentials:
     
     *   username: `richard@example.com`
     *   password: `password`
14.  In a separate private or incognito window, open the app at [http://localhost:3000](http://localhost:3000) and click Log in with FusionAuth .
     
15.  Click Create an account and create an account using your personal email address, name, and birthdate.
     
16.  Edit and save your own note. Your name appears at the top of the page and in the default note text.
     

Your Spring Boot app now provides unique notes for each user. Each user can independently edit and save their note. To see all of the notes, look for `note-<id>.txt` files in the `user_data` directory. To identify which note corresponds to which user, compare the `id` in the file name with the `id` field in the user's Source tab.

## Summary

In this QuickStart, FusionAuth handled login for your Spring Boot app:

*   Spring Security sent users to the FusionAuth login page and exchanged the authorization code for tokens, so the app never saw their passwords.
*   The security configuration 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.

Related

[Quickstarts FusionAuth QuickStart for Spring Boot API QuickStart integration of a Spring Boot API application action as a resource server with FusionAuth. spring boot quickstartspring security](https://fusionauth.io/docs/quickstarts/api/quickstart-java-springboot-api.md)
---

## 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.
- [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 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 Golang](https://fusionauth.io/docs/quickstarts/web/quickstart-golang-web.md): QuickStart integration of a Golang web application with FusionAuth using the CoreOS OIDC library.
- [FusionAuth QuickStart for Remix](https://fusionauth.io/docs/quickstarts/web/quickstart-javascript-remix-web.md): QuickStart integration of Javascript Remix web application with FusionAuth.
- [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 Laravel](https://fusionauth.io/docs/quickstarts/web/quickstart-php-laravel-web.md): QuickStart integration of PHP Laravel web application with FusionAuth.
- [FusionAuth QuickStart for PHP](https://fusionauth.io/docs/quickstarts/web/quickstart-php-web.md): QuickStart integration of PHP web application with FusionAuth.
- [FusionAuth QuickStart for Ruby on Rails](https://fusionauth.io/docs/quickstarts/web/quickstart-ruby-rails-web.md): QuickStart integration of Ruby on Rails web application with FusionAuth.
- [FusionAuth QuickStart for Rust with Actix](https://fusionauth.io/docs/quickstarts/web/quickstart-rust-actix-web.md): QuickStart integration of a Rust Actix 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.
