Recent Posts
Archives

Posts Tagged ‘SpringSecurity’

PostHeaderIcon [SpringIO2026] New in Spring Security 7: MFA, OAuth2 and more

Lecturer

Daniel Garnier-Moiroux is a software engineer on the Spring team at Broadcom, focusing on Spring Security, identity, and SSO concerns. He contributes actively to Spring Security and related projects, including work on one-time tokens, passkeys, multi-factor authentication, and Model Context Protocol security. He is also writing the Manning book Testing Spring Boot Applications (early access). Previously affiliated with VMware Tanzu, he has spoken widely on Spring Security architecture, passwordless authentication, and practical security patterns. He maintains an active presence through his personal site and open-source contributions under the handle Kehrlann.

Abstract

Spring Security 7 delivers a long-requested multi-factor authentication capability together with modular configuration improvements, OAuth 2 enhancements on both the authorization-server and client sides, stricter defaults such as mandatory PKCE, dynamic client registration, and experimental support for securing Model Context Protocol endpoints. This article examines the design of the new MFA APIs built around factor granted authorities and authorization-manager factories, shows how modular customizers avoid overwriting Spring Boot defaults, details the OAuth 2 changes, and outlines migration considerations from version 6.

Multi-Factor Authentication APIs

Multi-factor authentication had been requested since issue 2603 was opened in 2013. Spring Security 7 finally ships first-class support. Authentication factors are modelled as special GrantedAuthority instances of type FactorGrantedAuthority. Each successful login method (password, one-time token, passkey, and so on) records both the factor type and the timestamp at which it was obtained.

The annotation @EnableMultiFactorAuthentication installs the necessary infrastructure and accepts a list of required factors. When the list is supplied at the global level, every protected endpoint demands those factors. For finer control the same requirement can be expressed per endpoint by obtaining an AuthorizationManager from a multi-factor factory:

AuthorizationManagerFactory mfa =
  AuthorizationManagerFactories.multiFactor()
    .requireFactors(
      FactorGrantedAuthority.PASSWORD,
      FactorGrantedAuthority.OTT)
    .build();

http.authorizeHttpRequests(authz ->
  authz.requestMatchers("/admin/**")
       .access(mfa.hasRole("ADMIN")));

Because the underlying API is the familiar access(AuthorizationManager), arbitrary combinations become possible. The utility AuthorizationManagers.allOf and anyOf allow mixing recent-password checks with role checks, or applying MFA only to administrators while ordinary users need only a password. Time-based constraints are expressed with AllRequiredFactorsAuthorizationManager and a duration; an authentication older than the chosen window is rejected and the user is forced to re-authenticate with the missing factor.

The design deliberately re-uses the existing authorization infrastructure rather than inventing a parallel authentication pipeline. Consequently any custom AuthorizationManager already written for complex access rules can be composed with factor requirements without further framework changes.

Modular Configuration and Safer Defaults

A common pain point in earlier versions was that declaring a single SecurityFilterChain bean completely replaced Spring Boot’s auto-configured security. Spring Security 7 introduces Customizer<HttpSecurity> (and the corresponding customizers for individual configurers such as OAuth2AuthorizationServerConfigurer or CsrfConfigurer). Applications that need only a small adjustment—making one path public, adding a claim to the OpenID Provider Configuration endpoint, or tweaking CSRF—now supply a focused customizer bean. Boot defaults remain intact and the change is applied on top of them.

Several legacy constructs have been removed or relocated. The classic “and()” DSL that closed configuration blocks is gone; lambda style is mandatory. The OAuth 2 password grant has been dropped from the client because the OAuth 2 security best-current-practice document has long discouraged it. Kerberos support and the Spring Authorization Server project itself have been aligned to the same version numbering as the core Spring Security modules, simplifying release coordination.

OAuth 2 Enhancements on Server and Client

On the authorization-server side PKCE is now required by default. Clients that cannot yet produce a code challenge can disable the requirement, but the recommended posture is to keep it enabled even for confidential clients. Dynamic client registration, driven by the need to support Model Context Protocol agents that self-register, has been added. An admin client holding the client.create scope (or, for the more open MCP use-case, an unauthenticated registration endpoint) can POST a registration request and receive a generated client identifier and secret. Tokens used for registration are single-use, limiting abuse.

On the client side Spring Framework 7’s HTTP service clients receive first-class OAuth 2 support. A single bean of type OAuth2RestClientHttpServiceGroupConfigurer wires an OAuth2AuthorizedClientManager and a client-registration identifier into every declarative HTTP interface. The resulting code is free of manual RestClient interceptors yet still obtains and refreshes tokens automatically.

MCP Security and Migration Guidance

Because the Model Context Protocol specification continues to evolve rapidly, MCP security lives in a dedicated Spring AI community project rather than in core Spring Security. The same team members maintain both, and the intention is to graduate the work once the protocol stabilises. Starters on start.spring.io already expose experimental MCP server and client security options that rely on the OAuth 2 features described above.

Migration from Spring Security 6 is documented in a dedicated guide. Most applications that already use the lambda DSL and modern authorization managers require only dependency updates and the removal of the password-grant client code. Applications still relying on the old access-decision voters must move to the authorization-manager model; the deprecated classes remain available in a separate module for a transitional period.

Taken together, the release strengthens the security baseline while giving developers precise, composable tools for multi-factor scenarios and modern authorization flows.

Links:

PostHeaderIcon [SpringIO2025] Modern Authentication Demystified: A Deep Dive into Spring Security’s Latest Innovations @ Spring IO

Lecturer

Andreas Falk is an Executive Consultant at CGI, specializing in software architecture, application and cloud security, and identity and access management (IAM). As an iSAQB Certified Architect, security expert, trainer, and public speaker, he has over 25 years of experience in enterprise application development. Falk is renowned for his contributions to Spring Security, including workshops on reactive security and presentations on modern authentication mechanisms.

Abstract

This article provides an in-depth analysis of recent advancements in Spring Security, focusing on features introduced from version 6.3 onward. It examines compromised password checking, OAuth token exchange, one-time token login, and passkey authentication, alongside improvements in filter chain management and emerging specifications like Demonstrating Proof of Possession (DPoP). The discussion elucidates implementation strategies, security implications, and best practices for integrating these innovations into Spring-based applications.

Enhancements in Password Management and Token Handling

Spring Security 6.3 introduces compromised password checking, leveraging Troy Hunt’s Have I Been Pwned API to validate passwords against known breaches. Passwords are hashed before transmission, ensuring privacy. This feature integrates into password policies, enforcing minimum lengths (e.g., 12 characters) and maximums (up to 100), while permitting diverse characters, including emojis, to enhance security without undue restrictions.

Implementation involves registering a CompromisedPasswordChecker bean:

@Bean
public CompromisedPasswordChecker compromisedPasswordChecker() {
    return new HaveIBeenPwnedRestApiPasswordChecker();
}

This checker can be invoked in registration endpoints or policy validators, rejecting compromised inputs like “password” while accepting stronger alternatives.

OAuth token exchange addresses scenarios with multiple microservices, reducing attack surfaces by exchanging short-lived JSON Web Tokens (JWTs) for domain-specific ones. A client obtains a JWT, exchanges it at the authorization server for a scoped token, minimizing risks in high-stakes services like payments versus low-risk ones like recommendations.

Advanced Authentication Mechanisms: One-Time Tokens and Passkeys

One-time tokens (OTT) secure sensitive actions, such as password resets or transaction approvals, without persistent sessions. Spring Security supports OTT generation and validation, configurable via beans like OneTimeTokenService. Users receive tokens via email or SMS, granting temporary access.

Passkeys, based on WebAuthn and FIDO2, offer passwordless, phishing-resistant authentication using biometric or hardware keys. Spring Security’s PasskeyAuthenticationProvider integrates seamlessly, supporting registration and authentication flows. Devices like YubiKeys or smartphones generate public-private key pairs, with public keys stored server-side.

Example configuration:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(authz -> authz
            .anyRequest().authenticated()
        )
        .passkey(passkey -> passkey
            .passkeyAuthenticationProvider(passkeyAuthenticationProvider())
        );
    return http.build();
}

This enables biometric logins, eliminating passwords and enhancing usability.

Filter Chain Improvements and Emerging Specifications

Spring Security’s filter chain, often a source of configuration errors, now includes error detection for misordered chains in version 6.3+. Annotations like @Order ensure proper sequencing, preventing silent failures.

Version 6.4 adds OAuth2 support for the RestClient, automatic bearer token inclusion, and OpenSAML 5 for SAML assertions. Kotlin enhancements improve pre/post-filter annotations.

Demonstrating Proof of Possession (DPoP) in 6.5 binds tokens cryptographically to clients, thwarting theft in single-page applications (SPAs). Mutual TLS complements this for server-side frameworks. JWT profiles specify token types (e.g., access tokens), ensuring intended usage.

Pushed Authorization Requests (PAR) secure initial OAuth flows by posting parameters first, receiving a unique link devoid of sensitive data.

Implications for Secure Application Development

These innovations mitigate root causes of breaches—weak passwords and token vulnerabilities—promoting passwordless paradigms. Token exchange and DPoP reduce attack surfaces in microservices architectures. However, developers must address persistence for passkeys (e.g., database storage) and secure actuator endpoints.

Future versions (7.0+) mandate lambda DSL for configurations, removing deprecated code and defaulting to Proof Key for Code Exchange (PKCE) for all clients. Authorization server advancements, like multi-tenancy and backend-for-frontend patterns, facilitate scalable, secure ecosystems.

In conclusion, Spring Security’s evolution empowers developers to build resilient, user-friendly authentication systems, aligning with modern threats and standards.

Links:

PostHeaderIcon [DevoxxUK2025] Passkeys in Practice: Implementing Passwordless Apps

At DevoxxUK2025, Daniel Garnier-Moiroux, a Spring Security team member at VMware, delivered an engaging talk on implementing passwordless authentication using passkeys and the WebAuthn specification. Highlighting the security risks of traditional passwords, Daniel demonstrated how passkeys leverage cryptographic keys stored on devices like YubiKeys, Macs, or smartphones to provide secure, user-friendly login flows. Using Spring Boot 3.4’s new WebAuthn support, he showcased practical steps to integrate passkeys into an existing application, emphasizing phishing resistance and simplified user experiences. His live coding demo and insights into Spring Security’s configuration made this a compelling session for developers seeking modern authentication solutions.

The Problem with Passwords

Daniel opened by underscoring the vulnerabilities of passwords, often reused or poorly secured, leading to frequent breaches. He introduced passwordless alternatives, starting with one-time tokens (OTTs), which Spring Security supports for temporary login links sent via email. While effective, OTTs require cumbersome steps like copying tokens across devices. Passkeys, based on the WebAuthn standard, offer a superior solution by using cryptographic keys tied to specific domains, eliminating password-related risks. Supported by major browsers and platforms like Apple, Google, and Microsoft, passkeys enable seamless authentication via biometrics, PINs, or physical devices, combining convenience with robust security.

Understanding WebAuthn and Passkeys

Passkeys utilize asymmetric cryptography, where a private key remains on the user’s device (e.g., a YubiKey or iPhone) and a public key is shared with the server. Daniel explained the two-phase process: registration, where a key pair is generated and the public key is stored on the server, and authentication, where the server sends a challenge, the device signs it with the private key, and the server verifies it. This ensures phishing resistance, as keys are domain-specific and cannot be used on fraudulent sites. WebAuthn, a W3C standard backed by the FIDO Alliance, simplifies this process for developers by abstracting complex cryptography through browser APIs like navigator.credentials.create() and navigator.credentials.get().

Integrating Passkeys with Spring Security

Using a live demo, Daniel showed how to integrate passkeys into a Spring Boot 3.4 application. He added the spring-security-webauthn dependency and configured a security setup with the application name, relying party (RP) ID (e.g., localhost), and allowed origins. This minimal configuration enables a default passkey login page. For persistence, Spring Security 6.5 (releasing soon after the talk) offers JDBC support, requiring two tables: one for user credentials (storing public keys and metadata) and another linking passkeys to users. Daniel emphasized that Spring Security handles cryptographic validation, sparing developers from implementing complex WebAuthn logic manually.

Customizing the Passkey Experience

To enhance user experience, Daniel demonstrated creating a custom login page with a branded “Sign in with Passkey” button, styled with CSS (featuring a comic sans font for humor). He highlighted the need for JavaScript to interact with WebAuthn APIs, copying Spring Security’s Apache-licensed sample code for authentication flows. This involves handling CSRF tokens and redirecting users post-authentication. While minimal Java code is needed, developers must write some JavaScript to trigger browser APIs. Daniel advised using Spring Security’s defaults for simplicity but encouraged customization for production apps, ensuring alignment with brand aesthetics.

Practical Considerations and Feedback

Daniel stressed that passkeys are not biometric data but cryptographic credentials, synced across devices via password managers or iCloud Keychain without server involvement. For organizations using identity providers like Keycloak or Azure Entra ID, passkey support is often a checkbox configuration, reducing implementation effort. He encouraged developers to provide feedback on Spring Security’s passkey support via GitHub issues, emphasizing community contributions to refine features. For those interested in deeper WebAuthn mechanics, he recommended Ubico’s developer guide over the dense W3C specification, offering practical insights for implementation.

Links: