Fact-checked by Grok 2 weeks ago

Spring Security

Spring Security is a powerful and highly customizable and access-control framework that serves as the de-facto standard for securing Spring-based applications. It provides comprehensive support for , authorization, and protection against common web attacks such as , , and . Originating in late 2003 as the Acegi Security System for Spring—a standalone security framework for J2EE applications—it was integrated into the Spring portfolio toward the end of 2007 and rebranded as Spring Security. At its core, Spring Security employs a filter-based that integrates seamlessly with Servlet containers through the DelegatingFilterProxy, allowing it to intercept HTTP requests and apply security constraints before they reach the application logic. The framework's Security Filter Chain, managed by FilterChainProxy, delegates requests to specific chains of filters based on URL patterns, enabling fine-grained control over flows (e.g., via UsernamePasswordAuthenticationFilter or BasicAuthenticationFilter) and authorization decisions. This modular design supports both imperative (Servlet-based) and reactive (WebFlux-based) environments, with first-class integration into other Spring projects like , Spring MVC, and Spring Data for streamlined configuration and deployment. Spring Security emphasizes configurability, allowing developers to use annotation-driven security (e.g., @PreAuthorize for method-level ), XML-based declarations, or Java-based setups to enforce role-based or attribute-based policies. As of November 2025, the latest stable release is version 7.0.0, which requires 17+ and 7.0+, incorporating enhancements for 2.0, SAML, and JWT support while maintaining backward compatibility for enterprise-scale applications.

History and Development

Origins and Early Versions

Spring Security originated in late 2003 as the Acegi Security System for Spring, developed by Ben Alex to provide a flexible, open-source security framework tailored for Spring-based applications. This project addressed gaps in Java EE security standards, such as the Java Authentication and Authorization Service (JAAS), by offering more comprehensive support for declarative security in POJO-oriented architectures rather than relying solely on container-managed mechanisms. Acegi Security's first public release occurred in March 2004 under the 2.0, with core features centered on declarative security implemented through Spring's (AOP) proxies for method-level interception and . Ben Alex led the development, and the framework quickly gained traction within the Spring community for its superior flexibility compared to traditional J2EE container security, enabling easier customization and integration without . In early 2007, the project underwent a significant transition. On January 25, 2007, Ben Alex announced the rebranding to on the official , aiming to formalize its alignment with the Spring portfolio and enhance its visibility and support. Acegi Security became an official Spring subproject toward the end of 2007, culminating in the release of version 2.0 in April 2008, which marked the first fully integrated version under the new name.

Major Releases and Evolution

Spring Security's major releases have marked significant advancements in integration with the Spring ecosystem, adoption of modern security standards, and configuration paradigms. The project rebranded from Acegi Security and achieved its first official release as Spring Security 2.0.0 on April 15, 2008, which fully integrated the framework as a core Spring , replacing the standalone Acegi approach with seamless and support. This version introduced enhanced method-level security and initial support for RESTful services, laying the groundwork for broader adoption within Spring applications. Subsequent releases built on this foundation by simplifying configuration and aligning with evolving Java standards. Spring Security 3.0.0, released on December 23, 2009, introduced XML namespace configuration for declarative setup, reducing boilerplate code and enabling easier integration with Spring's application context. It also added support for the Spring Expression Language (SpEL) in security expressions, allowing dynamic authorization rules, and marked a shift toward annotation-based configurations in later 3.x updates, such as @PreAuthorize and @PostAuthorize for method security. By Spring Security 4.0.0, released on March 26, 2015, the framework incorporated Java 8 features like lambda expressions and streams for more concise security expressions and testing utilities. This version provided native support for Servlet 3.0 asynchronous processing, improving performance in web applications, and enhanced CSRF protection with improved token handling. It also deprecated certain legacy configuration options, encouraging migration to Java-based setups over XML. Spring Security 5.0.0, released on November 28, 2017, aligned closely with 5, introducing reactive security support via Spring WebFlux for non-blocking applications and comprehensive OAuth 2.0 resource server capabilities. Reactive modules became a core part of the framework, though optional for traditional servlet-based apps, and Java configuration was firmly established as the preferred method, with XML support marked for future deprecation. The release emphasized modern authentication protocols, including improvements. The 6.0 series, with its general availability announced on November 21, 2022, represented a major overhaul to meet contemporary security requirements, requiring 17 and 9 as baselines for better performance and security. It established 2.1 as the default baseline, incorporating stricter client authentication and proof-key-for-code-exchange (PKCE) enhancements, while adopting modern cryptographic standards such as for password hashing by default. XML namespace configuration was deprecated in favor of Java config and builder patterns, with removal planned for version 7.0. As of November 2025, Spring Security maintains parallel branches for compatibility, with the 5.x series receiving security patches alongside the active 6.x line, allowing gradual migrations for legacy applications. The latest stable release is version 7.0.0, issued on November 17, 2025, which introduces support for via annotations such as @EnableGlobalMultiFactorAuthentication and removes deprecated support entirely, signaling further evolution toward annotation-driven and reactive-first security models. The latest in the 6.x branch is 6.5.7, also released on November 17, 2025, providing maintenance updates and compatibility with 6.2.

Overview and Core Architecture

Fundamental Components

Spring Security's fundamental components provide the foundational building blocks for implementing and in applications, enabling developers to secure both web and non-web contexts through a modular and extensible . These components include core classes and interfaces that manage user identity, permissions, and security decisions, adhering to established security principles to ensure robust protection without unnecessary complexity. At the heart of this architecture is the SecurityContextHolder, a utility class responsible for storing the details of the current in a thread-bound manner. By default, it uses a ThreadLocal strategy to propagate the security context across method calls within the same thread, making authentication information accessible throughout the application's execution flow. This design allows seamless integration in multi-threaded environments typical of server-side applications, though it requires careful handling in asynchronous scenarios. For such cases, developers can configure alternative modes, such as MODE_INHERITABLETHREADLOCAL, which enables the security context to be inherited by child threads created from the parent thread, ensuring continuity in security checks during . The SecurityContext held by SecurityContextHolder contains an Authentication object, which represents the principal (typically a user) and encapsulates their credentials and granted permissions. This interface serves as the central representation of a user's identity post-authentication, storing details like the principal's name, authenticated status, and a collection of authorities. In non-web contexts, such as standalone Java applications or scheduled tasks, the Authentication object facilitates method-level security by providing the necessary identity information without relying on HTTP-specific mechanisms. The Authentication object is immutable once populated, promoting thread safety and preventing unauthorized modifications during runtime. Supporting is the UserDetailsService , which defines a for loading user-specific data, including username, , and authorities, from a persistent store like a database or in-memory repository. Implementations of this service are invoked by authentication providers to retrieve and validate user details during the process, allowing customization for various backends while maintaining a standardized . This component decouples user from the core logic, enabling flexible integration with external identity providers. For processing authentication requests, the AuthenticationManager interface acts as a delegate, coordinating multiple AuthenticationProvider implementations to validate credentials and return a fully populated Authentication object upon success. It supports pluggable providers for diverse authentication schemes, ensuring that the framework can handle complex scenarios without tight coupling to specific mechanisms. In web applications, this manager initializes the Authentication object stored in the SecurityContextHolder; in non-web contexts, it similarly populates the context for subsequent authorization checks. Authorization decisions rely on the AccessDecisionManager interface, which evaluates whether an authenticated principal has sufficient permissions to access a protected resource by consulting a set of voters against the Authentication object's authorities. This manager aggregates votes from configurable strategies, such as affirmative, consensus, or unanimous models, to determine access grants or denials. Permissions are represented through the GrantedAuthority interface, which encapsulates fine-grained roles or privileges assigned to the principal, typically as strings like "ROLE_USER" or custom scopes. These authorities enable precise control, aligning with of least privilege by granting only the minimal permissions necessary for a user's role, thereby reducing the in both web and non-web environments. The interplay among these components ensures a cohesive security model: the SecurityContextHolder provides global access to the Authentication object, which is populated via the AuthenticationManager and UserDetailsService, while the AccessDecisionManager uses GrantedAuthority instances from that object to enforce access controls. In web contexts, this foundation supports HTTP-based security; in non-web scenarios, it underpins annotation-driven or programmatic checks, offering consistent behavior across application types. These components are orchestrated within the security filter chain for servlet-based applications, where they integrate with request processing.

Security Filter Chain Mechanics

Spring Security's servlet-based architecture relies on a chain of filters to intercept and process HTTP requests, ensuring constraints are applied before reaching the application logic. The DelegatingFilterProxy serves as the , integrating Spring Security into the servlet by delegating requests to the Spring-managed FilterChainProxy bean. This proxy then routes the request to one or more SecurityFilterChain instances, each configured with a specific set of filters tailored to particular patterns or security requirements. The default filter chain, when using standard HttpSecurity configuration, includes a predefined sequence of filters such as SecurityContextPersistenceFilter for establishing the , HeaderWriterFilter for headers, CsrfFilter for protection, UsernamePasswordAuthenticationFilter for form-based , ExceptionTranslationFilter for handling exceptions, and AuthorizationFilter for decisions. This chain begins with early filters like ChannelProcessingFilter, which enforces secure () or insecure (HTTP) channel requirements based on configuration, followed by setup and filters before and . The ordering is strictly enforced to respect dependencies, such as performing prior to ; deviations can lead to vulnerabilities. Custom filters can be inserted using methods like addFilterBefore, addFilterAfter, or addFilterAt on HttpSecurity, allowing precise placement relative to existing filters. During request processing, each in examines the HttpServletRequest and may modify it, invoke the next filter via chain.doFilter(), or short-circuit by directly writing to the HttpServletResponse—for instance, redirecting unauthenticated users to a login page or rejecting invalid CSRF tokens. The FilterChainProxy selects the appropriate SecurityFilterChain using a RequestMatcher, ensuring only relevant filters are applied; if no match is found, the request proceeds unsecured unless a default chain catches it. This modular design, configured via HttpSecurity for web-specific setups, enables zoned security where different paths (e.g., public APIs vs. admin areas) use distinct chains. A significant evolution occurred in version 3.1, introducing support for multiple SecurityFilterChain instances within a single FilterChainProxy, configurable via multiple <http> elements in XML or equivalent Java configuration. This allows defining separate chains for different request patterns, such as stateless authentication for REST endpoints and form-based login for web UIs, with the first matching chain taking precedence. For non-blocking applications built with Spring WebFlux, Spring Security 5.0+ provides reactive support through WebFilterChain, which processes requests asynchronously using reactive streams, adapting the filter mechanics to handle backpressure and non-blocking I/O without servlet dependencies.

Authentication

Authentication Mechanisms

Spring Security offers a variety of built-in authentication mechanisms to verify user identities, ranging from traditional username/password-based approaches to and token-based methods. These mechanisms integrate with the framework's core architecture, allowing developers to configure authentication flows that suit different application requirements, such as applications, APIs, or enterprise environments.

Built-in Authentication Providers

The includes several pre-configured AuthenticationProvider implementations that handle specific scenarios. The DaoAuthenticationProvider is a key provider for database-backed , relying on a UserDetailsService to load user details and a PasswordEncoder to validate credentials against stored hashed passwords. It processes UsernamePasswordAuthenticationToken objects, retrieving the UserDetails for the provided username and comparing the submitted password using the encoder, enabling seamless integration with relational databases or other data sources via custom UserDetailsService implementations. For directory services, the LdapAuthenticationProvider facilitates authentication against LDAP servers, including , without requiring a traditional UserDetailsService since LDAP bind operations do not expose passwords. It supports authentication, where user credentials are used directly to bind to the LDAP directory, and password comparison modes for verifying hashed values, often combined with an LdapAuthoritiesPopulator to map directory attributes to Spring Security authorities. This provider is particularly useful in enterprise settings for centralizing user management. The RememberMeAuthenticationProvider supports persistent login functionality, processing RememberMeAuthenticationToken instances generated from secure or tokens stored on the client side. It requires a shared for token validation and a UserDetailsService to reconstruct the user's details upon presentation of a valid remember-me , allowing users to remain authenticated across sessions without re-entering credentials. This provider enhances while maintaining through token expiration and hashing.

Authentication Mechanisms

Spring Security supports form-based as a standard web authentication method, where users submit credentials via an , typically handled by the UsernamePasswordAuthenticationFilter. Upon submission, the filter creates an token and delegates to the AuthenticationManager; successful triggers session creation and redirection, while failures redirect to an error page, with customizable login pages and CSRF protection enabled by default. HTTP Basic authentication provides a simple, stateless mechanism for access, sending credentials in the Authorization header as base64-encoded username:password pairs per 7617. The BasicAuthenticationFilter extracts and validates these credentials, prompting clients with a WWW-Authenticate challenge on unauthorized requests, making it suitable for non-browser clients like mobile apps or scripts, though it requires to mitigate risks. Digest authentication addresses Basic's clear-text vulnerabilities by using a challenge-response based on RFC 2617, where the server issues a and the client responds with a hashed digest of credentials and request details. Implemented via DigestAuthenticationFilter, it supports or password storage but is deprecated for new applications due to weaker hashing compared to modern adaptive algorithms, recommending migration to token-based alternatives. X.509 certificate authentication leverages client certificates for mutual TLS (mTLS) verification, extracting the subject's distinguished name from the presented certificate to identify the user. The X509AuthenticationFilter maps the certificate details to a principal using regex patterns on the subject DN, integrating with a UserDetailsService for authority loading, ideal for environments requiring strong, non-interactive identity proof like internal networks or devices. Since version 5.2, Spring Security has provided native support for JWT bearer tokens as part of its 2.0 Resource Server features, validating self-contained Web Tokens via a JwtDecoder that checks signatures, expiration, and claims against a configured issuer. This enables stateless for and APIs, with scopes mapped to authorities, using libraries like JOSE + JWT for decoding and verification.

Extensibility

Developers can extend by implementing the AuthenticationProvider interface, which defines methods to support custom Authentication tokens and perform bespoke verification logic, such as integrating with external identity providers or proprietary protocols. Instances are registered with the ProviderManager to participate in the , allowing fallback to other providers if unsupported, thus supporting hybrid or multi-provider setups. Post-authentication behavior is customizable through handlers like AuthenticationSuccessHandler and AuthenticationFailureHandler, invoked after successful or failed attempts to manage redirects, session adjustments, or additional checks. For instance, the success handler can redirect to a or trigger auditing, while the failure handler logs attempts or enforces lockouts, providing hooks for tailored user experiences without altering core provider logic.

Specific Features

Password encoding is handled by the BCryptPasswordEncoder, which became the default under the DelegatingPasswordEncoder in Spring Security 5.0, applying the algorithm with adaptive work factors (default strength of 10) to resist brute-force attacks by slowing verification to approximately one second per password. This shift from the insecure NoOpPasswordEncoder ensures hashed storage for all new credentials, with legacy support via prefixed encodings. As of Spring Security 7.0 (released November 2025), the framework provides native support for (MFA) through declarative configuration, enabling requirements for multiple factors such as passwords and one-time tokens (). This is achieved using annotations like @EnableMultiFactorAuthentication and factor-specific authorities (e.g., PASSWORD_AUTHORITY, OTT_AUTHORITY) in authorization rules, with options for global or selective enforcement on specific endpoints. Custom AuthenticationProvider implementations remain available for advanced or legacy multi-step flows, such as integrating TOTP or hardware tokens via provider chaining.

Authentication Process Flow

The authentication process in Spring Security begins when an incoming HTTP request enters the security filter chain, where it is intercepted by one or more authentication filters configured for the application, such as UsernamePasswordAuthenticationFilter for form-based login or BasicAuthenticationFilter for HTTP Basic authentication. These filters extract the principal and credentials from the request—typically a username and password submitted via a form or headers—and encapsulate them into a pre-authenticated Authentication object, such as UsernamePasswordAuthenticationToken. This object is then submitted to the central AuthenticationManager for verification. The AuthenticationManager, usually implemented as a ProviderManager, delegates the authentication attempt to a chain of AuthenticationProvider instances, each responsible for a specific mechanism; for example, DaoAuthenticationProvider loads user details via a UserDetailsService implementation and validates the credentials against stored data, such as hashed passwords from a database. If a provider successfully authenticates the token—confirming the credentials match the loaded UserDetails—it returns a fully populated Authentication object with authorities and principal details; otherwise, it throws an exception, and the manager proceeds to the next provider until exhaustion or success. Upon successful authentication, the Authentication is stored in the SecurityContextHolder (typically using a ThreadLocal strategy for the current request thread), making the authenticated user's identity available throughout the application. Additionally, Spring Security invokes session management strategies, including protection against session fixation attacks by invalidating the existing session (if any) and creating a new one, migrating necessary attributes to prevent session hijacking. For unauthenticated requests that do not trigger explicit attempts, Spring Security automatically applies anonymous by setting an AnonymousAuthenticationToken in the SecurityContextHolder, assigning a default anonymous user with limited authorities to allow graceful handling of resources without full . On success, an AuthenticationSuccessHandler is invoked, which by default redirects the user to a configured success or forwards the request; the process also clears sensitive credentials from the Authentication object for security and publishes an success event. In contrast, failure triggers an AuthenticationException, handled by an AuthenticationFailureHandler that delegates to an AuthenticationEntryPoint—such as LoginUrlAuthenticationEntryPoint for form , which redirects to a page, or a simple response sender for APIs resulting in an HTTP 401 Unauthorized status. Forbidden access (post- but lacking permissions) may yield , though this is configurable via exception translation in the filter chain. This core authentication flow has been a foundational element since the early versions of Spring Security, evolving from its Acegi Security origins to support modern requirements. With the release of Spring Security 5.0 in 2018, enhancements introduced reactive flows compatible with Spring WebFlux, using non-blocking operators like Mono<Authentication> for handling credentials and providers in asynchronous environments. For stateless authentication in RESTful APIs, applications can configure session creation policies to avoid HTTP session usage altogether—relying instead on token-based mechanisms like JWT—ensuring scalability without server-side state.

Authorization

Access Control Strategies

Spring Security employs and resource-based to enforce at the web layer, ensuring that only authenticated and authorized users can interact with protected endpoints. This approach originated in the Acegi Security System for Spring, which began development in late and introduced foundational mechanisms that evolved into modern Spring Security features. The core strategy revolves around pattern matching for , using Ant-style syntax to define rules for paths, such as requiring the ROLE_ADMIN authority for all requests under /admin/**. This allows developers to specify granular permissions, where wildcards like * match single path segments and ** match multiple segments, enabling broad yet precise coverage of resource hierarchies. Additionally, HTTP method restrictions can be layered on these patterns, for instance, permitting anonymous GET requests to /public/** while mandating authentication for operations on the same paths. Configuration of these strategies occurs primarily through the HttpSecurity.authorizeHttpRequests() method, which defines a chain of rules evaluated in order against incoming requests. Role-based uses hasRole("ADMIN") to check for prefixed authorities like ROLE_ADMIN, whereas authority-based employs hasAuthority("ADMIN") for unprefixed permissions, allowing for more flexible, custom granular controls without the automatic ROLE_ prefix. For example, the following lambda-style permits public to static resources, restricts administrative paths to admins, and denies all other requests:
java
http.authorizeHttpRequests(authorize -> authorize
    .requestMatchers("/static/**").permitAll()
    .requestMatchers("/admin/**").hasRole("ADMIN")
    .anyRequest().denyAll());
This DSL style, introduced in Spring Security 5.2, enhances readability by leveraging lambdas and eliminating the need for explicit .and() chaining between rules. Key features augment these strategies for enhanced security. Explicit matchers like permitAll() allow unrestricted access to public endpoints, denyAll() blocks all traffic to sensitive paths, and IP-based restrictions via hasIpAddress("192.168.1.1") in SpEL expressions (e.g., .access("hasIpAddress('192.168.1.1')")) provide network-level filtering for added defense in depth. These elements collectively form a robust for URL-level , balancing accessibility with protection. CSRF protection and channel security are configured separately and covered in advanced features.

Method and Instance Security

Spring Security provides fine-grained security at the method and instance levels through annotation-driven mechanisms integrated with (AOP). This approach allows developers to enforce rules directly on methods and domain objects, complementing URL-based access controls by targeting code-level invocations. From its origins, Spring Security has leveraged Spring AOP to intercept method calls, enabling declarative security without invasive changes to application code. To enable method security, developers configure @EnableMethodSecurity (replacing the deprecated @EnableGlobalMethodSecurity in Security 5.6 and later) on a @Configuration class, which activates proxy-based interception using Spring AOP. This setup registers interceptors like AuthorizationManagerBeforeMethodInterceptor for pre-method checks and supports both JDK dynamic proxies and CGLIB for class-based proxies, ensuring security applies to public methods in Spring-managed beans. For domain object security, the framework extends this to instance-level protections, such as filtering collections or validating return objects post-invocation. Annotation-based security includes @PreAuthorize for evaluating expressions before method execution, preventing unauthorized access; for example, @PreAuthorize("hasRole('ADMIN')") restricts a method to users with the ADMIN role using Spring Expression Language (SpEL). Similarly, @PostAuthorize performs checks after execution, often on return values, such as @PostAuthorize("returnObject.owner == authentication.name") to ensure users access only their own data. The @Secured annotation offers a simpler role-based alternative, like @Secured("ROLE_ADMIN"), but requires explicit enabling via securedEnabled = true in configuration. Spring Security also supports JSR-250 standard annotations, including @RolesAllowed("ROLE_USER") for role checks, @PermitAll for unrestricted access, and @DenyAll for blocking all invocations, activated with jsr250Enabled = true. SpEL expressions in these annotations provide dynamic evaluation, accessing context like authentication.principal or custom methods for complex logic. Instance-level features focus on securing domain objects through after-invocation mechanisms. @PostFilter filters return collections based on SpEL, e.g., @PostFilter("filterObject.owner == [authentication](/page/Authentication).name") returns only user-owned items, while @PreFilter applies similar logic to input parameters. For broader security, @EnableMethodSecurity with object-return uses proxies to wrap returned instances, enforcing rules like ownership via AuthorizationProxyFactory. These post-invocation checks integrate seamlessly with AOP, allowing data filtering without altering core business methods. Spring Security extends method security to reactive applications using WebFlux (since 5.2), enabled via @EnableReactiveMethodSecurity. This leverages Reactor's Context and ReactiveSecurityContextHolder to propagate authentication in non-blocking flows, supporting the same annotations on methods returning Publisher types like Mono or Flux; for instance, @PreAuthorize("hasRole('USER')") public Mono<Account> readAccount(Long id);. Key improvements include native AOP support, Kotlin coroutine compatibility, and the AuthorizationManager API for streamlined custom rules (enhanced in 6.x), differing from servlet-based security by handling asynchronous streams without blocking.

Advanced Features

Protection Against Common Attacks

Spring Security incorporates several mechanisms to defend against prevalent web vulnerabilities, primarily through its security filter chain and HTTP response headers. These protections target threats such as (CSRF), session-related exploits, and , ensuring robust defense for Spring-based applications without requiring extensive custom implementation.

CSRF Protection

CSRF attacks are mitigated in Spring Security via the synchronizer pattern, enforced by the CsrfFilter which generates and validates a unique for each session. This filter ensures that non-safe HTTP methods, like and PUT, include the —either as a hidden form field automatically inserted by Spring's form tags or as a custom header for requests—to verify the request's legitimacy. For stateless RESTful APIs, where sessions are not used, CSRF protection can be explicitly disabled via configuration to avoid overhead, such as using .csrf(csrf -> csrf.disable()) in HttpSecurity. This -based approach has been enabled by default since Spring Security 3.2, providing out-of-the-box safeguards for traditional web applications.

Session Management

Spring Security's session management features prevent unauthorized access and reuse of sessions, including controls for concurrency, fixation attacks, and handling. Concurrent session control limits the number of simultaneous sessions per user—configured via maximumSessions(n) in SessionManagementConfigurer—and can either expire the oldest session or block new s when the limit is reached, requiring a HttpSessionEventPublisher for event tracking. On logout, the framework automatically invalidates the HTTP session using SecurityContextLogoutHandler, clearing the security context and removing the session to prevent post-logout access. Session fixation attacks, where an attacker forces a victim's session ID, are countered by generating a new session ID post-authentication; since version 4.0, this leverages HttpServletRequest.changeSessionId() (available in Servlet 3.1) as the default strategy, with alternatives like migrateSession for older environments. To enhance cookie security, Spring Security sets the HttpOnly flag—introduced in version 3.1 for Servlet 3.0 containers—to block JavaScript access to session cookies, and the Secure flag to restrict transmission to HTTPS-only connections, configurable via sessionManagement().sessionCreationPolicy().

Additional Attack Mitigations

Clickjacking, which tricks users into unintended actions via framed content, is prevented by default through the X-Frame-Options: DENY header, set by Spring Security's FrameOptionsConfig, blocking the application's pages from being embedded in iframes. Since version 4.1, developers can configure advanced security headers for broader protection: HTTP Strict Transport Security (HSTS) enforces HTTPS with defaults like max-age=31536000; includeSubDomains, mitigating man-in-the-middle attacks, while Content Security Policy (CSP) restricts resource loading (e.g., script-src 'self') to counter cross-site scripting (XSS). These headers, managed via HttpSecurity.headers(), align with OWASP Top 10 risks such as injection (A1:2017 via CSP) and security misconfiguration (A6:2017 via HSTS), promoting comprehensive vulnerability mitigation.

Integration with Modern Protocols

Spring Security offers robust integration with OAuth 2.0 and its evolving successor, OAuth 2.1, enabling applications to act as both resource servers and clients in secure authorization flows. As a resource server, it validates access tokens, supporting both JWT and opaque token formats through dependencies like spring-boot-starter-oauth2-resource-server. JWT decoding is handled via the Nimbus JOSE + JWT library, utilizing NimbusJwtDecoder for signature verification against issuer metadata or public keys. Client-side support, provided by spring-boot-starter-oauth2-client, facilitates grants such as authorization code and client credentials, with configurable ClientRegistration for endpoints and scopes. From version 6.0 onward, Spring Security establishes a baseline compliance with OAuth 2.1 draft specifications, incorporating best practices like exact redirect URI matching and deprecation of insecure flows. In version 7.0, support for the deprecated resource owner password credentials grant was removed to further align with OAuth 2.1 security recommendations. Additionally, version 7.0 introduces support for Demonstrating Proof-of-Possession (DPoP)-bound access tokens, which bind tokens to a client's public key proof to prevent token theft and replay attacks. For public clients, Proof Key for Code Exchange (PKCE) is mandatory starting in Spring Security 6.1, enhancing security against code interception by requiring dynamic challenges in the . This aligns with 2.0 extensions for native and single-page applications, where clients without secrets generate a code verifier and challenge to bind requests. Reactive applications benefit from filters introduced in version , using WebClient with ExchangeFilterFunction for non-blocking token propagation and validation in WebFlux environments. OpenID Connect (OIDC) integration builds on OAuth 2.0 foundations, providing identity layer features for user authentication. Spring Security validates ID tokens issued by OIDC providers, extracting claims like subject and audience during the code flow. Since version 5.2, it supports OIDC discovery endpoints, allowing automatic of ClientRegistration from the provider's .well-known/openid-[configuration](/page/Configuration) metadata, which includes , , and userInfo endpoints. This streamlines setup for providers like or , ensuring issuer verification and introspection without manual endpoint specification. SAML 2.0 support enables web (SSO) through framework components, replacing the deprecated Spring SAML extension. The extension, previously handling SAML and , was moved into Spring Security's starting in version 5.2, with full migration guidance for 6.x applications emphasizing RelyingPartyRegistration for configuration. This includes support for requests, assertion validation, and logout flows using OpenSAML libraries, ensuring compatibility with identity providers like . In version 6.x, deprecated extension artifacts like spring-security-saml2-[core](/page/Core) are no longer maintained, directing users to modules such as spring-security-saml2-service-provider for generation and binding.

Configuration and Integration

Basic Setup Approaches

Spring Security offers several foundational approaches to configure security in Java-based web applications, primarily through Java-based configuration and auto-configuration in . The core mechanism involves annotating a configuration class with @EnableWebSecurity, which activates Spring Security's web security support and integrates it with Spring MVC by registering the springSecurityFilterChain servlet filter. This annotation enables the definition of security rules via beans, such as SecurityFilterChain, which customize HTTP security behaviors like authentication and authorization. Historically, annotation-driven configuration relied on extending the WebSecurityConfigurerAdapter class to override methods like configure(HttpSecurity http), providing a straightforward way to set up authentication and access controls. However, this approach was deprecated in Spring Security 5.7.0-M2 to promote a more modular, component-based configuration model. In Spring Security 6.0, the recommended replacement is the lambda (DSL), which allows concise configuration of SecurityFilterChain beans using lambda expressions for better readability and flexibility. For instance, a basic lambda DSL setup might look like this:
java
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authz -> authz
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin(withDefaults());
        return http.build();
    }
}
This example permits access to public endpoints while requiring for others, enabling form-based by default. For testing and prototyping, Spring Security supports in-memory user storage through the InMemoryUserDetailsManager, which allows defining users and roles directly in code without a database. A simple implementation involves creating a UserDetailsService bean:
java
@Bean
public [UserDetailsService](/page/User) userDetailsService() {
    [UserDetails](/page/User) user = [User](/page/User).withDefaultPasswordEncoder()
        .username("[user](/page/User)")
        .password("[password](/page/Password)")
        .roles("[USER](/page/User)")
        .build();
    return new InMemoryUserDetailsManager([user](/page/User));
}
This setup uses a encoder suitable only for , as environments require stronger hashing. For persistent storage, JDBC authentication integrates with relational databases using a DataSource and predefined SQL queries to retrieve user credentials and authorities. Spring Security provides default queries, such as SELECT username, password, enabled FROM users WHERE username = ? for , assuming a schema with users and authorities tables. Configuration involves a JdbcDaoAuthProvider bean wired to the DataSource, enabling database-backed user management. In Spring Boot applications, bootstrapping Spring Security is streamlined via the spring-boot-starter-security dependency, which triggers auto-configuration to secure all HTTP endpoints with HTTP Basic by default upon classpath detection. This minimal setup generates a random password for the default "" account, logged at startup, and protects resources while allowing form login customization if needed. Since Spring Security 5.0, password encoding has migrated to the DelegatingPasswordEncoder, a composite encoder that prefixes encoded passwords with an identifier (e.g., {[bcrypt](/page/Bcrypt)}) to support multiple algorithms and facilitate upgrades without re-encoding existing data. Additionally, CSRF protection is enabled by default for browser-based clients but should be disabled for non-browser consumers, as these are not vulnerable to attacks. A basic configuration thus yields both form login and Basic out of the box, providing immediate security for web applications.

Extensions with Spring Ecosystem

Spring Security seamlessly integrates with through auto-configuration mechanisms that simplify securing applications, particularly for OAuth2 and endpoints. When Spring Security is on the , automatically secures web applications, including the /error , and provides a default user with username "user" and a random password logged at startup. Developers can customize this via properties such as spring.security.user.name=admin and spring.security.user.password=secret. For OAuth2, auto-configuration activates with dependencies like spring-security-oauth2-client, enabling client registrations via properties (e.g., spring.security.oauth2.client.registration.my-client.client-id=abcd and spring.security.oauth2.client.registration.my-client.client-secret=password), supporting both OAuth2 and Connect with issuer URIs. endpoints are secured by default; customization uses EndpointRequest to define access rules based on paths like management.endpoints.web.base-path. As of 3.x (aligned with 6.x), it requires 6.x to align with 10 and 6.0 baselines. Starting with 4.0 (November 2025), it requires 7.0 to align with 11 and 7.0 baselines. In reactive environments, Spring Security provides non-blocking authentication support via Spring WebFlux, introduced in version 5.0 released on November 28, 2017. The SecurityWebFilterChain serves as the core configuration for reactive web security, analogous to HttpSecurity in servlet stacks but optimized for asynchronous processing. This enables event-driven security filters that handle authentication without blocking threads, integrating with for scalable applications. Spring Security extends to other Spring projects for specialized use cases. With Spring Cloud, it integrates via Spring Cloud Gateway using filters like TokenRelay to propagate OAuth2 access tokens downstream, requiring spring-boot-starter-oauth2-client and configuration in YAML or Java DSL (e.g., filters: - TokenRelay=). The SaveSession filter ensures security details persist with Spring Session. For data access, integration with Spring Data JPA allows security-aware queries through the spring-security-data module; a SecurityEvaluationContextExtension bean enables expressions like @Query("select m from Message m where m.to.id = ?#{ principal?.id }") to reference the authenticated principal. In GraphQL applications, Spring Security secures endpoints via HTTP URL patterns and fine-grained annotations like @PreAuthorize on resolvers, with context propagation for authenticated access control in both MVC and WebFlux setups. Version 6.5 enhances cloud-native observability with automatic Micrometer context propagation, supporting distributed tracing in service mesh environments. As of November 17, 2025, Spring Security 7.0.0 was released, featuring modular configuration for Servlet and WebFlux, enhanced OAuth 2.0 support (including PKCE enabled by default and HTTP service clients), new password encoders like Argon2, and removal of deprecated features for alignment with Spring Framework 7.0.

References

  1. [1]
    Spring Security
    Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based ...Javadoc · Getting Started (Servlet) · Getting Spring Security
  2. [2]
    Spring Security
    Spring Security is a framework that provides authentication, authorization, and protection against common attacks.Javadoc · Getting Started · Getting Spring Security · Security RequestBuilders
  3. [3]
  4. [4]
    Architecture :: Spring Security
    Logging. Spring Security provides comprehensive logging of all security related events at the DEBUG and TRACE level.
  5. [5]
    [PDF] Three Approaches to Securing Your JSF-Spring - Huihoo
    What is it? • Open source project by Ben Alex (2003). • Who uses it ... security and Acegi framework address different security problems. • No simple ...
  6. [6]
    Why the name Acegi? - Spring
    Sometime around November 2003, I wrote what eventually became Acegi Security. I put it into a ZIP file and shot it across to Rod and Juergen. I ...
  7. [7]
    Spring Security 2.0.0 Released!
    Apr 15, 2008 · After almost two years of development, Spring Security 2.0.0 is now available for download. This significant new release replaces Acegi Security ...
  8. [8]
    Spring (Acegi) Security 2.0 Adds OpenID Support, REST ... - InfoQ
    Apr 28, 2008 · Rod Johnson, the President and CEO of SpringSource, announced the release of Spring Security 2.0.0, which replaces Acegi Security as the ...Missing: 2007 | Show results with:2007
  9. [9]
    Spring Security 3.0.0 Released
    Spring Security 3.0.0 Released. Releases | Luke Taylor | December 23, 2009 | 0 Comments. We're pleased to an announce the release of Spring Security 3.0.0.
  10. [10]
    Spring Security 3.0.0.M1 Released
    Jun 3, 2009 · We're pleased to announce that the first milestone of Spring Security 3.0 is now available for download. The release is also available through ...
  11. [11]
    Spring Security 4.0.0 Released
    Mar 26, 2015 · I'm pleased to announce the release of Spring Security 4.0.0.RELEASE which closes over 175+ tickets. You can find the highlights below.
  12. [12]
    Spring Security 5.0.0.RELEASE Released
    Nov 28, 2017 · On behalf of the community, I'm pleased to announce the release of Spring Security 5.0.0.RELEASE. This release resolves 400+ tickets.
  13. [13]
    Spring Security 5.0.0 Released - InfoQ
    Dec 14, 2017 · Pivotal has released Spring Security 5.0.0, the first major release since 4.0.0, featuring OAuth support and support for project Reactor and ...
  14. [14]
    Spring Security 5.8 and 6.0 are now GA
    Nov 21, 2022 · We are pleased to announce the general availability of Spring Security 5.8, which is provided to simplify upgrading to 6.0.
  15. [15]
    Spring Security 2025-10 Releases
    Oct 20, 2025 · On behalf of the team and everyone who has contributed, I am pleased to announce the availability of Spring Security 7.0.0-RC1 , 6.4.12 and ...
  16. [16]
    Servlet Authentication Architecture :: Spring Security
    The SecurityContextHolder is where Spring Security stores the details of who is authenticated. Spring Security does not care how the SecurityContextHolder is ...
  17. [17]
    UserDetailsService :: Spring Security
    UserDetailsService is used by DaoAuthenticationProvider for retrieving a username, a password, and other attributes for authenticating with a username and ...
  18. [18]
    Authorization Architecture :: Spring Security
    The GrantedAuthority objects are inserted into the Authentication object by the AuthenticationManager and are later read by AccessDecisionManager instances when ...
  19. [19]
    Spring Security
    From Spring Security 3.1 it is now possible to use multiple http elements to define separate security filter chain configurations for different request patterns ...
  20. [20]
    Reactive Applications :: Spring Security
    ### Summary of Reactive Security Filter Chain Mechanics
  21. [21]
    Authentication :: Spring Security
    Spring Security provides comprehensive support for Authentication. We start by discussing the overall Servlet Authentication Architecture.Username/Password · Authentication Architecture · Remember Me · Mocking Users
  22. [22]
    DaoAuthenticationProvider :: Spring Security
    DaoAuthenticationProvider is an AuthenticationProvider implementation that uses a UserDetailsService and PasswordEncoder to authenticate a username and password ...
  23. [23]
    LDAP Authentication :: Spring Security
    Spring Security's LDAP-based authentication is used by Spring Security when it is configured to accept a username/password for authentication.
  24. [24]
    Remember-Me Authentication :: Spring Security
    Remember-me or persistent-login authentication refers to web sites being able to remember the identity of a principal between sessions.
  25. [25]
    Form Login :: Spring Security
    Spring Security provides support for username and password being provided through an HTML form. This section provides details on how form based authentication ...
  26. [26]
    Basic Authentication :: Spring Security
    This section provides details on how Spring Security provides support for Basic HTTP Authentication for servlet-based applications.Missing: mechanisms | Show results with:mechanisms
  27. [27]
    Digest Authentication :: Spring Security
    Digest Authentication tries to solve many of the weaknesses of Basic authentication, specifically by ensuring credentials are never sent in clear text across ...Missing: mechanisms | Show results with:mechanisms<|control11|><|separator|>
  28. [28]
    X.509 Authentication :: Spring Security
    The most common use of X.509 certificate authentication is in verifying the identity of a server when using SSL, most commonly when using HTTPS from a browser.
  29. [29]
    OAuth 2.0 Resource Server JWT :: Spring Security
    Resource Server will automatically configure itself to validate JWT-encoded Bearer Tokens. It achieves this through a deterministic startup process.
  30. [30]
    Password Storage :: Spring Security
    Prior to Spring Security 5.0, the default PasswordEncoder was NoOpPasswordEncoder , which required plain-text passwords. Based on the Password History section, ...
  31. [31]
    Authentication Persistence and Session Management - Spring
    Session fixation attacks are a potential risk where it is possible for a malicious attacker to create a session by accessing a site, then persuade another user ...
  32. [32]
    Anonymous Authentication :: Spring Security
    Anonymous authentication support is provided automatically when you use the HTTP configuration (introduced in Spring Security 3.0). You can customize (or ...
  33. [33]
  34. [34]
    Authorize HttpServletRequests :: Spring Security
    Spring Security allows you to model your authorization at the request level. For example, with Spring Security you can say that all pages under /admin require ...Authorizing an Endpoint · Matching by Servlet Path · Authorizing Requests
  35. [35]
    Spring Security - Lambda DSL
    Nov 21, 2019 · The release of Spring Security 5.2 includes enhancements to the DSL, which allow HTTP security to be configured using lambdas.Missing: evolution | Show results with:evolution
  36. [36]
    Cross Site Request Forgery (CSRF) :: Spring Security
    Spring Security protects against CSRF attacks by default for unsafe HTTP methods, such as a POST request, so no additional code is necessary.
  37. [37]
    Spring Security Reference
    If a client makes a request using HTTP rather than HTTPS, Spring Security can be configured to redirect to HTTPS. ... requires-channel Can be "http" or "https" ...<|separator|>
  38. [38]
    Method Security - Spring
    The primary way Spring Security enables method-level authorization support is through annotations that you can add to methods, classes, and interfaces.
  39. [39]
    EnableReactiveMethodSecurity :: Spring Security
    Spring Security supports method security by using Reactor's Context, which is set up by ReactiveSecurityContextHolder . The following example shows how to ...EnableReactiveMethodSecurit... · Using a Custom Authorization...
  40. [40]
    Handling Logouts :: Spring Security
    Spring Security will add its logout support and by default respond both to GET /logout and POST /logout.Understanding Logout's... · Customizing Logout URIs · Creating a Custom Logout...
  41. [41]
    Security HTTP Response Headers - Spring
    Letting your website be added to a frame can be a security issue. For ... A more modern approach to address clickjacking is to use X-Frame-Options header.Default Security Headers · Cache Control · Content Type Options · X-Frame-Options
  42. [42]
    OAuth2 :: Spring Security
    There are two types of Bearer tokens supported by Spring Security which each use a different component for validation: JWT support uses a JwtDecoder bean to ...OAuth 2.0 Resource Server JWT · OAuth 2.0 Login · OAuth 2.0 Resource Server
  43. [43]
  44. [44]
  45. [45]
  46. [46]
    OAuth 2.0 Login :: Spring Security
    ### Summary of OpenID Connect Support, ID Token Validation, and Discovery Endpoint Support from Spring Security 5.2
  47. [47]
    12. OAuth2 - Spring
    A ClientRegistration can be initially configured using discovery of an OpenID Connect Provider's Configuration endpoint or an Authorization Server's Metadata ...Missing: 5.2 | Show results with:5.2
  48. [48]
    SAML2 :: Spring Security
    Spring Security provides comprehensive SAML 2 support. This section discusses how to integrate SAML 2 into your servlet based application.SAML 2.0 Login Overview · SAML 2.0 Login · Saml 2.0 Metadata
  49. [49]
    SAML 2.0 Extension Migration :: Spring Security
    This document contains guidance for moving SAML 2.0 Service Providers from Spring Security SAML Extensions 1.x to Spring Security.
  50. [50]
    Java Configuration :: Spring Security
    The matching logic for multiple filter chains is performed by the FilterChainProxy . The default RequestMatcher matches any request to ensure Spring Security ...Hello Web Security Java... · HttpSecurity · Multiple HttpSecurity Instances
  51. [51]
    Spring Security without the WebSecurityConfigurerAdapter
    Feb 21, 2022 · In Spring Security 5.7.0-M2 we deprecated the WebSecurityConfigurerAdapter, as we encourage users to move towards a component-based security configuration.
  52. [52]
    Configuration Migrations :: Spring Security
    The Lambda DSL is present in Spring Security since version 5.2, and it allows HTTP security to be configured using lambdas.Missing: evolution | Show results with:evolution<|separator|>
  53. [53]
    JDBC Authentication :: Spring Security
    Spring Security provides default queries for JDBC-based authentication. This section provides the corresponding default schemas used with the default queries.
  54. [54]
    Getting Started | Securing a Web Application - Spring
    This guide walks you through the process of creating a simple web application with resources that are protected by Spring Security.
  55. [55]
    Cross Site Request Forgery (CSRF) :: Spring Security
    This means that requests with the HTTP GET , HEAD , OPTIONS , and TRACE methods should not change the state of the application. Synchronizer Token Pattern.What is a CSRF Attack? · Synchronizer Token Pattern · CSRF protection and JSON
  56. [56]
    Spring Security :: Spring Boot
    The default UserDetailsService has a single user. The user name is user , and the password is random and is printed at WARN level when the application starts, ...
  57. [57]
    Migrating to 6.0 :: Spring Security
    To migrate to 6.0, update to Spring Boot 3.0 and Spring Security 6, change javax to jakarta imports, compile with --parameters if needed, and perform ...
  58. [58]
    Spring Cloud Gateway
    Summary of each segment:
  59. [59]
    Spring Data Integration :: Spring Security
    Spring Security provides Spring Data integration that allows referring to the current user within your queries.
  60. [60]
    Security :: Spring GraphQL
    The path to a Web GraphQL endpoint can be secured with HTTP URL security to ensure that only authenticated users can access it.
  61. [61]
    What's New in Spring Security 6.5
    Spring Security 6.5 provides a number of new features. Below are the highlights of the release, or you can view the release notes for a detailed listing of ...Preparing for 7.0 · 6.4.12 · 6.4.13-snapshot