FusionAuth QuickStart for Spring Boot With Thymeleaf
On this page
This QuickStart explains how to add a login page and authentication to a website built with Spring Boot and Thymeleaf. 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:
If you use macOS or Windows, you need one of the following container management tools:
- Docker Desktop
- OrbStack (to use OrbStack for
docker composecommands after installation, rundocker context use orbstack) - Podman (in the commands below, replace
dockerwithpodman)
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:
-
Create a folder for the app and navigate into it:
$ mkdir spring-boot-quickstart && cd spring-boot-quickstart -
Create folders for the app's Java code and templates:
$ mkdir -p src/main/java/example/notes src/main/resources/templates -
Create a file named
pom.xmlwith the following contents, which adds Spring MVC and Thymeleaf:<?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> -
Create a file named
src/main/java/example/notes/NotesApplication.javawith the following code, which starts the app: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); } } -
Create a file named
src/main/java/example/notes/NotesController.javawith the following code: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
showmethod reads the note when the page loads, and thesavemethod saves it when the form is submitted. -
Create a file named
src/main/resources/templates/notes.htmlwith the following code, which displays the note in a form:<!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> -
Run the app:
$ mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=3000 -
Open the app at http://localhost:3000.
-
Type "Hello Spring Boot" in the text area, then click Save Changes .
-
In a file browser or terminal, look in the
spring-boot-quickstartfolder. You should see a new file namednote.txt, with text content "Hello Spring Boot". -
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:
-
Open your container management tool (listed in the prerequisites above).
-
From the
spring-boot-quickstartfolder, clone the GitHub repository for the FusionAuth instance you'll use with this QuickStart:$ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git -
Navigate into the cloned directory:
$ cd fusionauth-quickstart-app -
To start a local instance of FusionAuth, run the following command (omit the
-dflag to see all Docker logs):$ docker compose up -d -
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.
-
Open http://localhost:9011/admin to access the FusionAuth Admin UI.
-
Log in with these credentials:
- username:
admin@example.com - password:
password
- username:
-
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.
-
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:
-
Navigate out of the
fusionauth-quickstart-appfolder, back to thespring-boot-quickstartfolder that containspom.xmlandnote.txt:$ cd .. -
Replace the contents of
pom.xmlwith the following code, which adds the Spring Security OAuth2 client. This handles communication with our FusionAuth instance:<?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> -
Create a file named
src/main/resources/application.propertieswith the following contents (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):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=openidSpring Security finds the login and token endpoints in the OpenID Connect discovery document for the
issuer-uri. -
Create a file named
src/main/java/example/notes/SecurityConfig.javawith the following code: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:
addViewControllersshows thelogin.htmltemplate at/login.authorizeHttpRequestslets anyone open/login, and sends users who aren't logged in to/loginfor every other route.oauth2Loginsets/oauth-callbackas the route that receives the authorization code from FusionAuth. Spring Security exchanges the code for tokens, using PKCEAn extension to OAuth 2.0 that mitigates authorization code interception attacks using dynamic code verifiers and challenges., and validates the ID tokenA JSON Web Token that contains information about the authenticated user..- The
OidcClientInitiatedLogoutSuccessHandlersends the user to FusionAuth's logout endpoint so the FusionAuth session ends too, then back to the login page.
-
Create a file named
src/main/resources/templates/login.htmlwith the following code:<!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 thefusionauthclient registration inapplication.properties. -
Replace the contents of
src/main/resources/templates/notes.htmlwith the following code, which adds a Logout button:<!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:actionattributes add the CSRFAn attack in which a malicious site makes the user's browser send an unwanted request to a site where the user is logged in. The OAuth 2.0stateparameter protects the authorization flow from CSRF. token Spring Security requires for both forms. -
Run the app, which now uses FusionAuth login:
$ mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=3000 -
Open the app at http://localhost:3000 and click Log in with FusionAuth .
-
Log in with the following credentials:
- username:
richard@example.com - password:
password
- username:
-
Edit and save the note in the authenticated Spring Boot app.
-
Click Logout . FusionAuth ends your session and sends you back to the login page.
-
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:
-
Open the FusionAuth Admin UI at http://localhost:9011/admin.
-
Log in with the following credentials:
- username:
admin@example.com - password:
password
- username:
-
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
-
Click Save in the top right of the page to save your changes to self-service registration.
-
Navigate to Users -> Richard Hendricks -> Manage .
-
In the Source tab, look for the
firstNameandlastNamefields. That's what we'll use to personalize the UI for each user. We'll use the user'sidfield to generate a unique name for each user's note. -
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.
-
Replace the contents of
src/main/resources/application.propertieswith the following contents, which add theprofilescope so the ID token includes the user's first and last name: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 -
Replace the contents of
src/main/java/example/notes/NotesController.javawith 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: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. -
Replace the contents of
src/main/resources/templates/notes.htmlwith the following code, which greets the user by name:<!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> -
Run the app:
$ mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=3000 -
Open the app at http://localhost:3000 and click Log in with FusionAuth .
-
Log in with the following credentials:
- username:
richard@example.com - password:
password
- username:
-
In a separate private or incognito window, open the app at http://localhost:3000 and click Log in with FusionAuth .
-
Click Create an account and create an account using your personal email address, name, and birthdate.
-
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.
FusionAuth has many features (including Social Login, Single Sign-On, Passkeys, Multi-factor Authentication), most of which are free. This example app is a great starting point for learning about FusionAuth features.