Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 119 ยท Spring Boot

Spring Security: Two-Factor Auth, API Keys and Role Hierarchy

Add TOTP two-factor login, an API-key filter, a RoleHierarchy, @PreFilter and @PostFilter, view-level security tags and per-profile security switches to Spring Security.

Once login, registration and password reset work, real applications keep asking for the same handful of extras. Security teams want a second factor. Partners want to call your API with a key rather than a username and password. Administrators should automatically have everything managers have, so you want a role hierarchy. A list endpoint must return only the rows the caller may see. Templates should hide buttons the user can't use. And developers want security switched off on their laptops, without that switch ever reaching production.

Spring Security has an extension point for each of these, and most of them are small. This lesson shows the real configuration (read-only, since Spring can't run in this page's editor) and builds the interesting parts, TOTP codes, API-key checking, role hierarchies and post-filtering, in plain Java that you can run, so you see the algorithm and not only the annotation.

Two-factor authentication with TOTP

A password is "something you know". A second factor adds "something you have", most often an authenticator app on a phone. These apps implement TOTP (Time-based One-Time Password, RFC 6238), which is simple enough to build in a few lines:

  1. At enrollment the server creates a random secret (160 bits is the usual size) and shows it to the user as a QR code (an otpauth:// URI). The app stores it. The server stores it too.
  2. Every 30 seconds both sides compute HMAC-SHA1(secret, counter), where counter = floor(unixTime / 30), and turn the result into a 6-digit number with a rule called dynamic truncation.
  3. At login, after the password, the user types the current code. The server computes the expected code for the current time step (and usually one step before and after, to forgive clock drift) and compares.

No network is involved between the phone and the server after enrollment, which is why it works offline. The first example implements the algorithm and checks it against the official RFC 6238 test vectors (the secret 12345678901234567890 at known times), so you can be sure it is the real algorithm. It also shows replay protection and a base32 secret as used in the QR code.

Java TOTP from scratch (RFC 6238)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The three RFC vectors must match; if you change anything in code and they stop matching, it is no longer TOTP. Everything a library such as java-totp or googleauth does is in those 30 lines, plus QR rendering.

Wiring 2FA into Spring Security

Spring Security 7 ships one-time-token login (oneTimeTokenLogin()), which is meant for "magic link" emails, and has support for multi-factor authentication built on Authentication objects that carry the factors completed so far. TOTP itself isn't included, so the usual pattern still works on every version: a two-step login with an intermediate authority.

flowchart LR
  P["POST /login<br/>email + password"] --> Q{"2FA<br/>enabled?"}
  Q -- no --> D["Fully signed in<br/>ROLE_USER"]
  Q -- yes --> R["Half signed in<br/>PRE_AUTH_2FA only"]
  R --> S["POST /login/2fa<br/>6-digit code"]
  S --> T{"Code valid?"}
  T -- yes --> D
  T -- no --> R

A user who passed only the password gets one authority, PRE_AUTH_2FA, which opens just the code page.

  1. A success handler checks user.isTwoFactorEnabled(). If so, it replaces the authentication with one that has only the authority PRE_AUTH_2FA (and no ROLE_USER), and redirects to /login/2fa.
  2. The security rules allow /login/2fa for PRE_AUTH_2FA and every other URL only for real roles, so a half-signed-in user is stopped at every real page.
  3. The code controller verifies the TOTP code and, on success, stores a full Authentication with the user's real roles in the SecurityContext (and saves it to the session through SecurityContextRepository).
Java
@Bean
SecurityFilterChain webSecurity(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(auth -> auth
            .requestMatchers("/login", "/css/**").permitAll()
            .requestMatchers("/login/2fa").hasAuthority("PRE_AUTH_2FA")
            .anyRequest().hasRole("USER"))                      // PRE_AUTH_2FA alone is not enough
        .formLogin(form -> form
            .loginPage("/login")
            .successHandler(new TwoFactorSuccessHandler()));
    return http.build();
}

class TwoFactorSuccessHandler implements AuthenticationSuccessHandler {
    private final SecurityContextRepository repository = new HttpSessionSecurityContextRepository();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        AppUserDetails user = (AppUserDetails) authentication.getPrincipal();
        if (!user.isTwoFactorEnabled()) {
            response.sendRedirect("/dashboard");
            return;
        }
        var halfWay = new UsernamePasswordAuthenticationToken(
                user, null, List.of(new SimpleGrantedAuthority("PRE_AUTH_2FA")));
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(halfWay);
        repository.saveContext(context, request, response);
        response.sendRedirect("/login/2fa");
    }
}

@PostMapping("/login/2fa")
String verify(@RequestParam String code, Authentication authentication,
              HttpServletRequest request, HttpServletResponse response) {
    AppUserDetails user = (AppUserDetails) authentication.getPrincipal();
    if (!totp.verify(user.getTotpSecret(), code)) {
        attempts.recordFailure(user);                           // lock out after a few wrong codes
        return "redirect:/login/2fa?error";
    }
    var full = UsernamePasswordAuthenticationToken.authenticated(user, null, user.getAuthorities());
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    context.setAuthentication(full);
    repository.saveContext(context, request, response);
    return "redirect:/dashboard";
}

Details that decide whether 2FA is secure or only looks secure:

  • Only an enrolled secret counts. During enrollment, show the QR code, then ask the user to type one valid code before you switch 2FA on, so nobody locks themselves out with a mis-scanned code.
  • Limit attempts. A six-digit code has a million possibilities. Without a lockout or a delay, an attacker with a stolen password can try them all; reuse the failure counter from the previous lesson.
  • Refuse replays, as the example does, by storing the last accepted step.
  • Encrypt the secret at rest (it must be recoverable, so it is not hashed). Treat it like an API key.
  • Plan recovery. Give users 8 to 10 recovery codes at enrollment, shown once, stored hashed like passwords, single-use. Without them, a lost phone means a support ticket and an identity check.
  • Rotate the session id when the second factor succeeds (the repository save above plus changeSessionId() where needed), and require the code again before sensitive actions if your risk model calls for it.

For consumer apps, passkeys (WebAuthn) are the stronger modern alternative: Spring Security supports them since version 6.4, and they can't be phished the way a typed code can.

API keys

Machine-to-machine clients, such as a partner's server, a cron job or a mobile app's backend, often use a long random key sent in a header, usually X-API-Key or Authorization: Bearer .... Spring Security has no built-in key login, but a filter is short:

Java
@Component
class ApiKeyAuthenticationFilter extends OncePerRequestFilter {
    private final ApiKeyService keys;

    ApiKeyAuthenticationFilter(ApiKeyService keys) { this.keys = keys; }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String header = request.getHeader("X-API-Key");
        if (header != null) {
            Optional<ApiClient> client = keys.authenticate(header);
            if (client.isEmpty()) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid API key");
                return;                                          // stop the chain
            }
            var authentication = UsernamePasswordAuthenticationToken.authenticated(
                    client.get().name(), null, client.get().authorities());
            SecurityContext context = SecurityContextHolder.createEmptyContext();
            context.setAuthentication(authentication);
            SecurityContextHolder.setContext(context);
        }
        chain.doFilter(request, response);
    }
}

@Bean
SecurityFilterChain apiChain(HttpSecurity http, ApiKeyAuthenticationFilter apiKeyFilter) throws Exception {
    http.securityMatcher("/api/**")
        .addFilterBefore(apiKeyFilter, UsernamePasswordAuthenticationFilter.class)
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/admin/**").hasAuthority("SCOPE_admin")
            .anyRequest().authenticated())
        .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .csrf(csrf -> csrf.disable());                          // no cookies are used, see the Spring Security lesson
    return http.build();
}

Treat a key as a password for a machine, which sets the rules for the service behind it:

  • Generate keys with SecureRandom (at least 128 bits, base64url-encoded), and show the full key once.
  • Store only a hash (SHA-256 is enough for random 256-bit keys; slow password hashes would make every API call expensive). Add a short non-secret prefix or id to the key, such as ak_7f3k_<secret>, so you can look up the row by id and compare hashes in constant time, instead of hashing against every row.
  • Attach scopes or authorities to each key (read-only, write, admin) and an owner, so audit logs show who called.
  • Support revocation, rotation (two keys valid at once while a client switches) and expiry; log the key id, never the key.
  • Send keys only over HTTPS, and never accept them in URLs, where they end up in logs and browser history.

When you need more than a shared secret (user delegation, short lifetimes, standard tooling), use OAuth 2 tokens instead, as in JWT and OAuth 2 and the OAuth resource server lesson.

Role hierarchy

Roles often nest: an ADMIN can do everything a MANAGER can, who can do everything a USER can. Without help you would grant three roles to every admin, or write hasAnyRole("USER", "MANAGER", "ADMIN") in every rule. A RoleHierarchy declares the relationship once:

Java
@Bean
RoleHierarchy roleHierarchy() {
    return RoleHierarchyImpl.withDefaultRolePrefix()
            .role("ADMIN").implies("MANAGER")
            .role("MANAGER").implies("USER")
            .build();
}

A user with only ROLE_ADMIN is now treated as holding ROLE_MANAGER and ROLE_USER too, in authorizeHttpRequests rules and in @PreAuthorize checks. In current Spring Security versions a RoleHierarchy bean is picked up by both automatically; older code had to register it with a DefaultWebSecurityExpressionHandler and a method-security expression handler, so look for those when reading a legacy configuration. The hierarchy only adds reachable authorities for checks; it doesn't change what authentication.getAuthorities() contains.

Filtering collections: @PreFilter and @PostFilter

@PreAuthorize allows or denies a whole call. When a method takes or returns a collection, you may instead want to remove the elements the caller isn't allowed to touch. Method security can do it with SpEL, where filterObject stands for one element:

Java
@Service
class DocumentService {

    @PostFilter("hasRole('ADMIN') or filterObject.owner == authentication.name")
    public List<Document> findAll() {                         // runs the full query, then filters
        return repository.findAll();
    }

    @PreFilter("hasRole('ADMIN') or filterObject.owner == authentication.name")
    public void archiveAll(List<Document> documents) {        // forbidden elements are removed first
        documents.forEach(repository::archive);
    }
}

Both need @EnableMethodSecurity, and @PreFilter's argument must be a mutable collection (or an array, stream or map), because Spring removes elements from it. The big caveat is performance: @PostFilter loads every row and throws most of them away, and it breaks paging (a page of 20 can come back with 3 rows). For anything beyond small lists, put the rule in the query (findByOwner(authentication.name), a Spring Data query with @Query that uses ?#{authentication.name}, or a database view) and keep @PostFilter for small in-memory collections and as a belt-and-braces check.

The second example runs both ideas, a role hierarchy and a post filter, together with API-key authentication, in plain Java, so you can follow what Spring does at each step.

Java API keys, a role hierarchy and a post filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that the admin key was created with only ROLE_ADMIN, yet it is treated as ROLE_MANAGER and ROLE_USER as well, because the hierarchy computed the set at check time.

Security tags in views

Hiding a button the user can't use is a convenience, never protection: the server rule must still exist, because anyone can send the request by hand. With Thymeleaf, add the thymeleaf-extras-springsecurity6 module (pick the artifact whose name matches your Spring Security major version), declare the namespace, and use sec: attributes (Thymeleaf):

HTML
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<body>
  <p sec:authorize="isAuthenticated()">
    Signed in as <b sec:authentication="name">user</b>
  </p>
  <a sec:authorize="hasRole('ADMIN')" th:href="@{/admin}">Admin area</a>
  <a sec:authorize="isAnonymous()" th:href="@{/login}">Sign in</a>
</body>
</html>

In JSP pages the equivalent is the Spring Security tag library:

JSP
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

<sec:authorize access="hasRole('ADMIN')">
  <a href="${pageContext.request.contextPath}/admin">Admin area</a>
</sec:authorize>
Hello, <sec:authentication property="name"/>

Both evaluate the same expressions as @PreAuthorize, so a role hierarchy applies to them as well.

Turning security off per profile

Developers sometimes want to explore an API without logging in. The safe way is a profile-specific SecurityFilterChain, not a commented-out line:

Java
@Configuration
class SecurityProfiles {

    @Bean
    @Profile("dev")
    SecurityFilterChain openForLocalDevelopment(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
            .csrf(csrf -> csrf.disable());
        return http.build();
    }

    @Bean
    @Profile("!dev")
    SecurityFilterChain secured(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .formLogin(Customizer.withDefaults());
        return http.build();
    }
}

The !dev branch is the default, so forgetting to set a profile in production gives you the secure chain. The risk is the other way round: a production server started with SPRING_PROFILES_ACTIVE=dev is wide open. Guard against it by failing at startup if the dev profile is combined with a production signal, never putting dev in a file that ships as the default, and adding a test that asserts the production chain rejects an anonymous request. Excluding SecurityAutoConfiguration entirely, as old tutorials suggest, is worse: it removes the safety net for the whole application.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In TOTP, what do the server and the authenticator app both use to compute the same six-digit code?

    Both sides compute HMAC(secret, floor(time / 30)) and truncate it. No communication is needed after enrollment, which is why it works offline.
  2. 2. Why does a TOTP verifier usually accept the previous and next time step as well?

    Clocks drift by seconds. Accepting one step either side forgives that, while remembering the last used step prevents replay of a code.
  3. 3. How should the server store API keys?

    A random 256-bit key only needs a fast hash. The id lets you find the row, and the hash comparison should be constant-time. A leaked table then contains no usable keys.
  4. 4. With a RoleHierarchy of ADMIN implies MANAGER implies USER, what does a rule hasRole('USER') do for a user who only has ROLE_ADMIN?

    The hierarchy expands the user's authorities at check time. getAuthorities() itself is unchanged.
  5. 5. Why is @PostFilter a poor fit for a large, paged table?

    Filtering happens after the method returns. Put the owner or tenant condition into the query itself and keep @PostFilter for small collections.

Summary

  • TOTP is HMAC-SHA1(secret, time / 30) truncated to six digits (RFC 6238). Enroll with a random secret and a confirming code, verify with a small time window, refuse replays, limit attempts, encrypt the secret and issue recovery codes.
  • A two-step login can be built with an intermediate authority such as PRE_AUTH_2FA that opens only the code page; the full Authentication is stored after the code verifies.
  • An API-key filter (a OncePerRequestFilter added before the standard login filter) turns a header into an Authentication. Generate keys with SecureRandom, store a hash plus an id, attach scopes, support revocation and rotation, and send them only over HTTPS.
  • A RoleHierarchy bean declares that ADMIN implies MANAGER implies USER; web rules and method security both honor it.
  • @PreFilter and @PostFilter remove collection elements by SpEL on filterObject; for big data put the condition in the query instead.
  • sec:authorize (Thymeleaf) and <sec:authorize> (JSP) hide UI the user can't use, but never replace server-side rules. Disable security only through profile-specific SecurityFilterChain beans, with the secure chain as the default.

Next: JWT and OAuth 2 replaces keys and sessions with signed tokens.