Skip to main content

Sign-in for a Spring Boot app

Add sign-in to a Spring Boot app with properties only, and accept bearer tokens on the API routes.

RecipeReadyView source
Works with
JavaSpring Boot

What it shows​

  1. The starter reads lumoauth.login.* from application.yml and builds the OpenID Connect client registration of Spring Security.
  2. It adds a security filter chain. The paths in permit-all are open, and a signed-out browser goes to the hosted sign-in page.
  3. Spring Security keeps the session, and a controller reads the person as an OidcUser.
  4. The same chain accepts a bearer token on /api/me: the starter asks LumoAuth who the token belongs to.
  5. /logout ends the session of the app, and one bean sends the browser on to LumoAuth to end the session there.

Before you start​

  • Java 17 or later, Maven, and Spring Boot 4.
  • An API key with the scopes admin:clients:read and admin:clients:write. Create it in the portal under Applications & developer tools, API keys.
  • A confidential application with the redirect URI http://localhost:8080/login/oauth2/code/lumoauth. The setup script creates it.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYAn API key with the scopes admin:clients:read and admin:clients:write. Only the setup script uses it.
APP_URLOptional. The address of your app, when it is not http://localhost:8080. Only the setup script uses it. Set SERVER_PORT for the app.
LUMOAUTH_CLIENT_IDThe client ID of the application. The setup script prints it.
LUMOAUTH_CLIENT_SECRETThe client secret of the application. The setup script prints it.

The setup script creates the application through the Admin API and prints the variables of the app. LumoAuth shows a client secret only once, so each run makes a new secret.

node sign-in/spring-boot/setup.mjs
setup.mjs
// Creates the application that the Spring Boot app signs in with: a
// confidential application with the callback address of the app. Run it again
// at any time.
//
// node sign-in/spring-boot/setup.mjs
//
// The API key needs the scopes admin:clients:read and admin:clients:write.
// APP_URL is the address of your app. The default is http://localhost:8080.
import { call, list, printEnv } from '../../_lib/admin.mjs';

const appUrl = (process.env.APP_URL ?? 'http://localhost:8080').replace(/\/+$/, '');
const name = 'Spring Boot sign-in';
// Spring Security receives the code at this path. "lumoauth" is the
// registration ID of the starter.
const redirectUris = [`${appUrl}/login/oauth2/code/lumoauth`];

let secret;
let client = (await list('/admin/clients')).find((c) => c.name === name);
if (client) {
// LumoAuth shows a client secret only once, so a second run makes a new one.
await call('PATCH', `/admin/clients/${client.id}`, { redirectUris });
secret = (await call('POST', `/admin/clients/${client.id}/rotate-secret`)).data.secret;
} else {
client = (await call('POST', '/admin/clients', { name, redirectUris, isConfidential: true })).data;
secret = client.secret;
}

console.log(`Application "${name}" is ready. Its redirect URI is ${redirectUris[0]}.`);
printEnv({
LUMOAUTH_CLIENT_ID: client.clientId,
LUMOAUTH_CLIENT_SECRET: secret,
});

Copy the export lines that the script prints into the terminal where you start the app.

Sign-out returns to your app only when the address is registered. The Admin API has no field for it, so add it in the portal:

  1. Open Applications and select Spring Boot sign-in.
  2. Open the Configuration tab and go to the section Logout.
  3. Under Post-logout redirect URIs, enter http://localhost:8080/.
  4. Select Save configuration.

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. A browser signed in and out through the hosted page, and the API route was called with an access token.

sign-in/spring-boot/java/src/main/resources/application.yml
# The starter reads this section. The values come from the environment.
lumoauth:
url: ${LUMOAUTH_URL:https://app.lumoauth.dev}
org-id: ${LUMOAUTH_ORG_ID}
login:
# Setting the client ID turns sign-in on.
client-id: ${LUMOAUTH_CLIENT_ID}
client-secret: ${LUMOAUTH_CLIENT_SECRET}
# Open to everybody. Every other path needs a session or a bearer token.
permit-all: [/, /error, /favicon.ico, /actuator/health/**]

management:
endpoint:
health:
show-details: always
sign-in/spring-boot/java/src/main/java/com/example/signin/SignInApplication.java
package com.example.signin;

import java.util.List;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* A Spring Boot app with sign-in. The starter builds the client registration
* and the security filter chain from application.yml, so this class holds
* only the pages and the sign-out rule.
*
* cd sign-in/spring-boot/java && mvn spring-boot:run
*/
@SpringBootApplication
@RestController
public class SignInApplication {

public static void main(String[] args) {
SpringApplication.run(SignInApplication.class, args);
}

/** A public page: it is in lumoauth.login.permit-all. */
@GetMapping(value = "/", produces = "text/html")
String home(@AuthenticationPrincipal OidcUser user) {
if (user == null) {
return "<p>Nobody is signed in.</p><a href=\"/oauth2/authorization/lumoauth\">Sign in</a>";
}
return "<p>Signed in as " + user.getEmail() + ".</p>"
+ "<p><a href=\"/dashboard\">Dashboard</a> · <a href=\"/api/me\">Profile as JSON</a>"
+ " · <a href=\"/logout\">Sign out</a></p>";
}

/** A protected page: the filter chain sends a signed-out browser to sign-in. */
@GetMapping(value = "/dashboard", produces = "text/html")
String dashboard(@AuthenticationPrincipal OidcUser user) {
return "<h1>Dashboard</h1><p>User ID: " + user.getSubject() + "</p><a href=\"/\">Home</a>";
}

/** A protected API route: it accepts the session of a browser, or a bearer token. */
@GetMapping("/api/me")
Me me(Authentication authentication) {
List<String> authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).sorted().toList();
return new Me(authentication.getName(), authorities);
}

record Me(String sub, List<String> authorities) {}

/**
* Sign-out: after Spring Security ends the session of the app, this
* handler sends the browser to the logout endpoint of LumoAuth, which
* ends its session too and returns to the home page.
*/
@Bean
Customizer<HttpSecurity> signOutAtLumoAuth(ClientRegistrationRepository registrations) {
OidcClientInitiatedLogoutSuccessHandler handler = new OidcClientInitiatedLogoutSuccessHandler(registrations);
handler.setPostLogoutRedirectUri("{baseUrl}/");
return http -> http.logout(logout -> logout.logoutSuccessHandler(handler));
}
}
sign-in/spring-boot/java/pom.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>
<relativePath/>
</parent>

<groupId>com.example</groupId>
<artifactId>lumoauth-sign-in</artifactId>
<version>1.0.0</version>

<properties>
<java.version>17</java.version>
</properties>

<dependencies>
<!-- The LumoAuth starter. It brings the Java SDK with it. -->
<dependency>
<groupId>io.lumoauth</groupId>
<artifactId>lumo-auth-spring-boot-starter</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Sign-in for the browser. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<!-- Bearer tokens for the API. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<!-- The health indicator of LumoAuth. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
cd sign-in/spring-boot/java && mvn spring-boot:run

Check the result​

Open http://localhost:8080 in a browser, select Sign in, and sign in as a user of your organization.

Output
Signed out
GET / 200 Nobody is signed in.
GET /dashboard (a browser) 302 /oauth2/authorization/lumoauth
GET /api/me 401
GET /actuator/health/lumoauth 200 {"details":{"url":"https://app.lumoauth.dev","issuer":"https://app.lumoauth.dev/orgs/acme-corp/api/v1","orgId":"acme-corp"},"status":"UP"}

Signed in
GET / 200 Signed in as maya.chen@example.com.
GET /dashboard 200 User ID: 0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10
GET /api/me 200 {"sub":"0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10","authorities":["OIDC_USER","SCOPE_email","SCOPE_openid","SCOPE_profile"]}

With a bearer token
GET /api/me 200 {"sub":"0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10","authorities":["FACTOR_BEARER"]}
  • The browser holds only the cookie JSESSIONID, marked httpOnly. The tokens stay on the server.
  • /api/me answers 401 to a request with no session and no token. A browser that asks for a page gets a redirect to sign-in.
  • Sign out opens the confirmation page of Spring Security. After Log Out, the browser returns to /, and /dashboard shows the sign-in page again.
  • /actuator/health/lumoauth shows the lumoauth indicator with the status UP.

To call the API with a bearer token, send an access token of a signed-in person:

curl -H "Authorization: Bearer $ACCESS_TOKEN" http://localhost:8080/api/me

Limits​

  • The starter needs Spring Boot 4.
  • Without the bean signOutAtLumoAuth, /logout ends only the session of the app. The person stays signed in at LumoAuth.
  • The starter asks the UserInfo endpoint about each bearer token, on every request. It does not check the token locally.
  • A browser session has the authorities OIDC_USER and SCOPE_…. Roles are not among them.
  • For a bearer token, the starter adds one authority for each entry of the roles claim of UserInfo. LumoAuth sends that claim only when the application that issued the token has User roles turned on, on its Security tab under JWT claims. Print the authorities, as /api/me does, before you write a rule on a role name.
  • The filter chain of the starter steps back when the app defines its own SecurityFilterChain.