Authentication in Spring Boot
Updated on April 17, 2024Introduction
In this tutorial, you will learn:
- How to build a Spring Boot app with Java.
- How to secure your app and log in with OpenID Connect.
- How to add a logout feature.
Why Use Spring to Build Apps?
Spring Boot is one of the most popular frameworks for developing Java applications. It's used by companies around the world to simplify development and ease testing. If you want to be employed for years to come, Java is a good language to learn. Put those two together, and you have a winning combination!
OpenID Connect (OIDC) is an identity layer built on top of the OAuth 2.0 framework. It allows third-party applications to verify the identity of the end-user and to obtain basic user profile information.
In this guide, you'll learn how to use Java and Spring Boot to build a simple app that's secured with OIDC.
Set up a Development Environment
- Use your favorite text editor or IDE. We recommend using IntelliJ IDEA.
- Ensure that you have Java
17+
installed in your system. You can easily install it using SDKMAN!. - Windows commands in this guide are written for PowerShell.
Create an Auth0 account
If you already have an Auth0 account, you can log in to your tenant and continue to the next step.
Otherwise, sign up for a free Auth0 account.
During the sign-up process, you create something called an Auth0 Tenant, where you configure your use of Auth0.
Set up the Auth0 CLI
If you are not familiar with the Auth0 CLI, you can follow the "Auth0 CLI Basics" lab to learn how to build, manage, and test your Auth0 integrations from the command line.
There are different ways to install the Auth0 CLI, depending on your operating system.
Create a Spring Boot App
Use your browser and start.spring.io to create a new Spring Boot project with Spring Web and Okta dependencies.
This guide is using Spring Boot version
3.2.4
.
You can also create projects with the command line. To create a Gradle project, run the following command:
Run the following command if you prefer to create a Maven project instead:
The Okta Spring Boot starter is a thin wrapper around Spring Security's resource server, OIDC login, and OAuth client support. It secures all endpoints by default.
Navigate to the oidc-login
directory:
cd oidc-login
Then, run the app with the following command:
./gradlew bootRun
Open the http://localhost:8080
URL in your favorite browser. You'll be prompted to log in since the Okta Spring Boot starter secures all URLs by default. You won't be able to log in yet because you haven't configured OIDC yet.
Secure Spring Boot with OIDC
In a terminal, connect the Auth0 CLI to your Auth0 tenant.
auth0 login
auth0 login
command.Then, run the command below to create an OIDC application:
Copy the domain, client ID, and client secret of your app and paste it into the following input boxes:
When you enter a value in the input fields present on this page, any code snippet that uses such value updates to reflect it. Using the input fields makes copying and pasting code as you follow along easy.
Now, create an application.properties
file in the root directory to configure the Okta Spring Boot starter:
# trailing slash is important for issuerokta.oauth2.issuer=https://AUTH0-DOMAIN/okta.oauth2.client-id=AUTH0-CLIENT-IDokta.oauth2.client-secret=AUTH0-CLIENT-SECRET
Add this file to .gitignore
so you don't accidentally check it into source control:
application.properties
src/main/resources/application.properties
. However, we recommend you DO NOT include the client secret in this file for security reasons.Create a HomeController.java
class next to DemoApplication.java
:
Populate it with the following code:
package com.example.demo;import org.springframework.security.core.annotation.AuthenticationPrincipal;import org.springframework.security.oauth2.core.oidc.user.OidcUser;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerclass HomeController {@GetMapping("/")public String home(@AuthenticationPrincipal OidcUser user) {return "Hello, " + user.getFullName() + "!";}}
This controller is protected by Spring Security because the Okta Spring Boot starter auto-configures everything to be protected by default.
Stop and restart the app:
./gradlew bootRun
Open a browser and navigate to http://localhost:8080
. Log in with your Auth0 credentials or sign up as a new user and you should see your name displayed. If you don't have a user in your tenant yet, you can sign up with Google or create a new user with the Auth0 CLI:
auth0 users create
Implement a Profile Page and a Logout Button
First, ensure that RP-Initiated Logout End Session Endpoint Discovery is enabled in your Auth0 tenant. This is enabled by default for tenants created after 14 November 2023.
To implement a Logout feature, add dependencies for Thymeleaf and its Spring Security extension.
// # Modify the `build.gradle` file:implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
Add a template to render the homepage at src/main/resources/templates/home.html
:
Paste in the following code:
<html xmlns:th="http://www.thymeleaf.org"><head><title>Spring Boot + Auth0</title><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"></head><body><div class="container"><h2>Spring Boot + Auth0 Example</h2><div th:unless="${#authorization.expression('isAuthenticated()')}"><p>Hello!</p><p>If you're viewing this page then you have successfully configured and started this application.</p><p>This example shows you how to use the <a href="https://github.com/okta/okta-spring-boot">Okta Spring BootStarter</a> to add the <ahref="https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow">AuthorizationCode Flow</a> to your application.</p><p>When you click the login button below, you will be redirected to login. After youauthenticate, you will be returned to this application.</p></div><div th:if="${#authorization.expression('isAuthenticated()')}"><p>Welcome home, <span th:text="${#authentication.principal.attributes['name']}">Mary Coder</span>!</p><p>You have successfully authenticated with Auth0, and have been redirected back to this application.</p><p>Here are your user's attributes:</p><table class="table table-striped"><thead><tr><th>Claim</th><th>Value</th></tr></thead><tbody><tr th:each="item : ${claims}"><td th:text="${item.key}">Key</td><td th:id="${'claim-' + item.key}" th:text="${item.value}">Value</td></tr></tbody></table></div><form method="get" th:action="@{/oauth2/authorization/okta}"th:unless="${#authorization.expression('isAuthenticated()')}"><button id="login" class="btn btn-primary" type="submit">Login</button></form><form method="post" th:action="@{/logout}" th:if="${#authorization.expression('isAuthenticated()')}"><input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/><button id="logout" class="btn btn-danger" type="submit">Logout</button></form></div></body></html>
Update the HomeController#home()
method to return the user's claims:
import org.springframework.web.servlet.ModelAndView;import java.util.Collections;...@GetMapping("/")public ModelAndView home(@AuthenticationPrincipal OidcUser user) {return new ModelAndView("home", Collections.singletonMap("claims", user.getClaims()));}
Create a SecurityConfiguration.java
class to configure logout:
Paste in the following code:
package com.example.demo;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.security.web.authentication.logout.LogoutSuccessHandler;import static org.springframework.security.config.Customizer.withDefaults;@Configurationpublic class SecurityConfiguration {private final ClientRegistrationRepository clientRegistrationRepository;public SecurityConfiguration(ClientRegistrationRepository clientRegistrationRepository) {this.clientRegistrationRepository = clientRegistrationRepository;}private LogoutSuccessHandler logoutSuccessHandler() {OidcClientInitiatedLogoutSuccessHandler logoutSuccessHandler =new OidcClientInitiatedLogoutSuccessHandler(this.clientRegistrationRepository);// Sets the location that the end user's User Agent will be redirected to// after the logout has been performed at the ProviderlogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}");return logoutSuccessHandler;}@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()).oauth2Login(withDefaults()).logout(logout -> logout.logoutSuccessHandler(logoutSuccessHandler()));return http.build();}}
Restart your application and now you will be able to log in and log out. Huzzah!
Recap
In this tutorial, you learned how to build a Spring Boot app with Java, secure it with OIDC, and configure the logout feature. It's pretty sweet how you can create and configure a Spring Boot app with Auth0 so fast!
curl -G https://start.spring.io/starter.tgz -d dependencies=web,okta -d baseDir=oidc-login | tar -xzvf -auth0 apps create \--name "Spring Boot" \--description "Spring Boot Example" \--type regular \--callbacks http://localhost:8080/login/oauth2/code/okta \--logout-urls http://localhost:8080 \--reveal-secrets
Check out our other Spring Boot guides Authorization in Spring Boot and Role Based Access Control in Spring Boot to learn more about Auth0 security integration in Spring Boot Java applications.
Be sure to visit the Okta Spring Boot Starter's GitHub repository to stay informed on the latest developments and join the growing community of Spring Boot users who use Okta.