Java Spring Boot
The Okta Spring Boot Starter makes it easy to add login to your Spring Boot application. We recommend that you log in to follow this quickstart with examples configured for your account.
I want to integrate with my app
15 minutesI want to explore a sample app
2 minutesGet a sample configured with your account settings or check it out on Github.
Using Spring WebFlux?
This tutorial uses Spring MVC. If you are using Spring WebFlux, the steps to add authentication are similar, but some of the implementation details are different. Refer to the Spring Boot WebFlux Sample Code to see how to integrate Auth0 with your Spring Boot WebFlux application.
Configure Auth0
Get Your Application Keys
When you signed up for Auth0, a new application was created for you, or you could have created a new one. You will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.
You need the following information:
- Domain
- Client ID
- Client Secret
Configure Callback URLs
A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated. The callback URL for your app must be added to the Allowed Callback URLs field in your Application Settings. If this field is not set, users will be unable to log in to the application and will get an error.
Configure Logout URLs
A logout URL is a URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the returnTo
query parameter. The logout URL for your app must be added to the Allowed Logout URLs field in your Application Settings. If this field is not set, users will be unable to log out from the application and will get an error.
Configure Spring Boot Application
Add dependencies
To integrate your Spring Boot application with Auth0, include the Okta Spring Boot Starter in your application's dependencies.
If you're using Gradle, you can include these dependencies as shown below.
plugins {
id 'java'
id 'org.springframework.boot' version '3.1.4'
id 'io.spring.dependency-management' version '1.1.3'
}
implementation 'com.okta.spring:okta-spring-boot-starter:3.0.5'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
Was this helpful?
If you are using Maven:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.5</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>com.okta</groupId>
<artifactId>okta-spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
</dependencies>
Was this helpful?
Configure Spring Security
The Okta Spring Boot Starter makes it easy to configure your application with Auth0. The sample below uses an application.yml
file, though you can also use properties files or any of the other supported externalization mechanisms.
# src/main/resources/application.yml
okta:
oauth2:
issuer: https://{yourDomain}/
client-id: {yourClientId}
client-secret: YOUR_CLIENT_SECRET
# The sample and instructions above for the callback and logout URL configuration use port 3000.
# If you wish to use a different port, change this and be sure your callback and logout URLs are
# configured with the correct port.
server:
port: 3000
Was this helpful?
Add Login to Your Application
To enable user login with Auth0, create a class that will register a SecurityFilterChain, and add the @Configuration
annotation.
package com.auth0.example;
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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2Login(withDefaults());
return http.build();
}
}
Was this helpful?
The Okta Spring Boot Starter will use the client configuration you defined earlier to handle login when a user visits the /oauth2/authorization/okta
path of your application. You can use this to create a login link in your application.
<!-- src/main/resources/templates/index.html -->
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<body>
<div sec:authorize="!isAuthenticated()">
<a th:href="@{/oauth2/authorization/okta}">Log In</a>
</div>
<div sec:authorize="isAuthenticated()">
<p>You are logged in!</p>
</div>
</body>
</html>
Was this helpful?
Be sure to create or update a controller to render your view.
package com.auth0.example;
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;
/**
* Controller for the home page.
*/
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model, @AuthenticationPrincipal OidcUser principal) {
return "index";
}
}
Was this helpful?
Checkpoint
Add the login link to your application. When you click it, verify that your application redirects you to the Auth0 Universal Login page and that you can now log in or sign up using a username and password or a social provider.
Once that's complete, verify that Auth0 redirects you to your application and that you are logged in.
Add Logout to Your Application
Now that users can log into your application, they need a way to log out. By default, when logout is enabled, Spring Security will log the user out of your application and clear the session. To enable successful logout of Auth0, you can provide a LogoutHandler
to redirect users to your Auth0 logout endpoint (https://{yourDomain}/v2/logout
) and then immediately redirect them to your application.
In the SecurityConfig
class, provide a LogoutHandler
that redirects to the Auth0 logout endpoint, and configure the HttpSecurity
to add the logout handler:
package com.auth0.example;
import org.springframework.beans.factory.annotation.Value;
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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.io.IOException;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Value("${okta.oauth2.issuer}")
private String issuer;
@Value("${okta.oauth2.client-id}")
private String clientId;
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/", "/images/**").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(withDefaults())
// configure logout with Auth0
.logout(logout -> logout
.addLogoutHandler(logoutHandler()));
return http.build();
}
private LogoutHandler logoutHandler() {
return (request, response, authentication) -> {
try {
String baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();
response.sendRedirect(issuer + "v2/logout?client_id=" + clientId + "&returnTo=" + baseUrl);
} catch (IOException e) {
throw new RuntimeException(e);
}
};
}
}
Was this helpful?
You can then update your view to POST to the /logout
endpoint (Spring Security provides this by default) to enable users to log out.
<div sec:authorize="isAuthenticated()">
<p>You are logged in!</p>
<form name="logoutForm" th:action="@{/logout}" method="post">
<button type="submit" value="Log out"/>
</form>
</div>
Was this helpful?
Checkpoint
Add the logout link in the view of your application. When you click it, verify that your application redirects you the address you specified as one of the "Allowed Logout URLs" in the "Settings" and that you are no longer logged in to your application.
Show User Profile Information
You can retrieve the profile information associated with logged-in users through the OidcUser class, which can be used with the AuthenticationPrincipal annotation.
In your controller, add the user's profile information to the model:
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model, @AuthenticationPrincipal OidcUser principal) {
if (principal != null) {
model.addAttribute("profile", principal.getClaims());
}
return "index";
}
}
Was this helpful?
You can then use this profile information in your view, as shown below.
<div sec:authorize="isAuthenticated()">
<img th:src="${profile.get('picture')}" th:attr="alt=${profile.get('name')}"/>
<h2 th:text="${profile.get('name')}"></h2>
<p th:text="${profile.get('email')}"></p>
<a th:href="@{/logout}">Log Out</a>
</div>
Was this helpful?
Checkpoint
Verify that you can display the user name or any other user
property after you have logged in.