Spring Security Reference


Ben Alex , Luke Taylor , Rob Winch , Gunnar Hillert , Joe Grandja , Jay Bryant , Eddú Meléndez , Josh Cummings


Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.

Table of Contents

I. Preface
1. Prerequisites
2. Spring Security Community
2.1. Getting Help
2.2. Becoming Involved
2.3. Source Code
2.4. Apache 2 License
2.5. Social Media
3. What’s New in Spring Security 5.2
3.1. Servlet
3.2. WebFlux
3.3. Core
4. Getting Spring Security
4.1. Release Numbering
4.2. Usage with Maven
4.2.1. Spring Boot with Maven
4.2.2. Maven Without Spring Boot
4.2.3. Maven Repositories
4.3. Gradle
4.3.1. Spring Boot with Gradle
4.3.2. Gradle Without Spring Boot
4.3.3. Gradle Repositories
5. Project Modules
5.1. Core — spring-security-core.jar
5.2. Remoting — spring-security-remoting.jar
5.3. Web — spring-security-web.jar
5.4. Config — spring-security-config.jar
5.5. LDAP — spring-security-ldap.jar
5.6. OAuth 2.0 Core — spring-security-oauth2-core.jar
5.7. OAuth 2.0 Client — spring-security-oauth2-client.jar
5.8. OAuth 2.0 JOSE — spring-security-oauth2-jose.jar
5.9. OAuth 2.0 Resource Server — spring-security-oauth2-resource-server.jar
5.10. ACL — spring-security-acl.jar
5.11. CAS — spring-security-cas.jar
5.12. OpenID — spring-security-openid.jar
5.13. Test — spring-security-test.jar
6. Samples
II. Servlet Applications
7. Hello Spring Security
7.1. Hello Spring Security (Boot)
7.1.1. Updating Dependencies
7.1.2. Starting Hello Spring Security Boot
7.1.3. Spring Boot Auto Configuration
7.2. Hello Spring Security (Java Configuration)
7.2.1. Updating Dependencies
7.2.2. Minimal @EnableWebSecurity Configuration
7.2.3. Using AbstractSecurityWebApplicationInitializer
7.3. Hello Spring Security (XML)
7.3.1. Updating Dependencies
7.3.2. Minimal <http> Configuration
7.3.3. web.xml Configuration
8. Architecture and Implementation
8.1. Technical Overview
8.1.1. Runtime Environment
8.1.2. Core Components
SecurityContextHolder, SecurityContext and Authentication Objects
The UserDetailsService
8.1.3. Authentication
What is authentication in Spring Security?
Setting the SecurityContextHolder Contents Directly
8.1.4. Authentication in a Web Application
Authentication Mechanism
Storing the SecurityContext between requests
8.1.5. Access-Control (Authorization) in Spring Security
Security and AOP Advice
Secure Objects and the AbstractSecurityInterceptor
8.2. Core Services
8.2.1. The AuthenticationManager, ProviderManager and AuthenticationProvider
Erasing Credentials on Successful Authentication
8.2.2. UserDetailsService Implementations
In-Memory Authentication
9. Authentication
9.1. In-Memory Authentication
9.2. JDBC Authentication
9.3. LDAP Authentication
9.3.1. Overview
9.3.2. Using LDAP with Spring Security
9.4. Configuring an LDAP Server
9.4.1. Using an Embedded Test Server
9.4.2. Using Bind Authentication
9.4.3. Loading Authorities
9.5. Implementation Classes
9.5.1. LdapAuthenticator Implementations
Common Functionality
9.5.2. Connecting to the LDAP Server
9.5.3. LDAP Search Objects
9.5.4. LdapAuthoritiesPopulator
9.5.5. Spring Bean Configuration
9.5.6. LDAP Attributes and Customized UserDetails
9.6. Active Directory Authentication
9.6.1. ActiveDirectoryLdapAuthenticationProvider
Active Directory Error Codes
9.7. LDAP Java Configuration
9.8. AuthenticationProvider
9.8.1. AuthenticationProvider Java Configuration
9.8.2. AuthenticationProvider XML Configuration
9.9. UserDetailsService
9.10. Password Encoding
9.10.1. Password History
9.10.2. DelegatingPasswordEncoder
Password Storage Format
Password Encoding
Password Matching
Getting Started Experience
9.10.3. BCryptPasswordEncoder
9.10.4. Argon2PasswordEncoder
9.10.5. Pbkdf2PasswordEncoder
9.10.6. SCryptPasswordEncoder
9.10.7. Other PasswordEncoders
9.10.8. Password Encoder XML Configuration
9.11. The Authentication Manager and the Namespace
9.12. Session Management
9.12.1. Detecting Timeouts
9.12.2. Concurrent Session Control
9.12.3. Session Fixation Attack Protection
9.12.4. SessionManagementFilter
9.12.5. SessionAuthenticationStrategy
9.12.6. Concurrency Control
Querying the SessionRegistry for currently authenticated users and their sessions
9.13. Remember-Me Authentication
9.13.1. Overview
9.13.2. Simple Hash-Based Token Approach
9.13.3. Persistent Token Approach
9.13.4. Remember-Me Interfaces and Implementations
9.14. OpenID Support
9.14.1. Attribute Exchange
9.15. Anonymous Authentication
9.15.1. Overview
9.15.2. Configuration
9.15.3. AuthenticationTrustResolver
9.16. Pre-Authentication Scenarios
9.16.1. Pre-Authentication Framework Classes
9.16.2. Concrete Implementations
Request-Header Authentication (Siteminder)
Java EE Container Authentication
9.17. Java Authentication and Authorization Service (JAAS) Provider
9.17.1. Overview
9.17.2. AbstractJaasAuthenticationProvider
JAAS CallbackHandler
JAAS AuthorityGranter
9.17.3. DefaultJaasAuthenticationProvider
DefaultJaasAuthenticationProvider Example Configuration
9.17.4. JaasAuthenticationProvider
9.17.5. Running as a Subject
9.18. CAS Authentication
9.18.1. Overview
9.18.2. How CAS Works
Spring Security and CAS Interaction Sequence
9.18.3. Configuration of CAS Client
Service Ticket Authentication
Single Logout
Authenticating to a Stateless Service with CAS
Proxy Ticket Authentication
9.19. X.509 Authentication
9.19.1. Overview
9.19.2. Adding X.509 Authentication to Your Web Application
9.19.3. Setting up SSL in Tomcat
9.20. Run-As Authentication Replacement
9.20.1. Overview
9.20.2. Configuration
9.21. Form Login
9.21.1. Form Login Java Configuration
9.21.2. Form Login XML Configuration
Form and Basic Login Options
9.22. Basic and Digest Authentication
9.22.1. BasicAuthenticationFilter
9.22.2. Configuration
9.23. DigestAuthenticationFilter
9.23.1. Configuration
9.24. Handling Logouts
9.24.1. Logout Java Configuration
9.24.2. Logout XML Configuration
9.24.3. LogoutHandler
9.24.4. LogoutSuccessHandler
9.24.5. Further Logout-Related References
9.25. Setting a Custom AuthenticationEntryPoint
10. Authorization
10.1. Authorization Architecture
10.1.1. Authorities
10.1.2. Pre-Invocation Handling
The AccessDecisionManager
Voting-Based AccessDecisionManager Implementations
10.1.3. After Invocation Handling
10.1.4. Hierarchical Roles
10.2. Secure Object Implementations
10.2.1. AOP Alliance (MethodInvocation) Security Interceptor
Explicit MethodSecurityInterceptor Configuration
10.2.2. AspectJ (JoinPoint) Security Interceptor
10.3. Expression-Based Access Control
10.3.1. Overview
Common Built-In Expressions
10.3.2. Web Security Expressions
Referring to Beans in Web Security Expressions
Path Variables in Web Security Expressions
10.3.3. Method Security Expressions
@Pre and @Post Annotations
Built-In Expressions
10.4. Authorize Requests
10.5. Method Security
10.5.1. EnableGlobalMethodSecurity
10.5.2. GlobalMethodSecurityConfiguration
10.5.3. The <global-method-security> Element
10.5.4. Adding Security Pointcuts using protect-pointcut
10.6. Domain Object Security (ACLs)
10.6.1. Overview
10.6.2. Key Concepts
10.6.3. Getting Started
11. OAuth2
11.1. OAuth 2.0 Login
11.1.1. Spring Boot 2.x Sample
Initial setup
Setting the redirect URI
Configure application.yml
Boot up the application
11.1.2. Spring Boot 2.x Property Mappings
11.1.3. CommonOAuth2Provider
11.1.4. Configuring Custom Provider Properties
11.1.5. Overriding Spring Boot 2.x Auto-configuration
Register a ClientRegistrationRepository @Bean
Provide a WebSecurityConfigurerAdapter
Completely Override the Auto-configuration
11.1.6. Java Configuration without Spring Boot 2.x
11.1.7. Advanced Configuration
OAuth 2.0 Login Page
Redirection Endpoint
UserInfo Endpoint
ID Token Signature Verification
OpenID Connect 1.0 Logout
11.2. OAuth 2.0 Client
11.2.1. Core Interfaces / Classes
OAuth2AuthorizedClientRepository / OAuth2AuthorizedClientService
OAuth2AuthorizedClientManager / OAuth2AuthorizedClientProvider
11.2.2. Authorization Grant Support
Authorization Code
Refresh Token
Client Credentials
Resource Owner Password Credentials
11.2.3. Additional Features
Resolving an Authorized Client
11.2.4. WebClient integration for Servlet Environments
Providing the Authorized Client
Defaulting the Authorized Client
11.3. OAuth 2.0 Resource Server
11.3.1. Dependencies
11.3.2. Minimal Configuration for JWTs
Specifying the Authorization Server
Startup Expectations
Runtime Expectations
11.3.3. Specifying the Authorization Server JWK Set Uri Directly
11.3.4. Overriding or Replacing Boot Auto Configuration
Using jwkSetUri()
Using decoder()
Exposing a JwtDecoder @Bean
11.3.5. Configuring Trusted Algorithms
Via Spring Boot
Using a Builder
From JWK Set response
11.3.6. Trusting a Single Asymmetric Key
Via Spring Boot
Using a Builder
11.3.7. Trusting a Single Symmetric Key
11.3.8. Configuring Authorization
Extracting Authorities Manually
11.3.9. Configuring Validation
Customizing Timestamp Validation
Configuring a Custom Validator
11.3.10. Configuring Claim Set Mapping
Customizing the Conversion of a Single Claim
Adding a Claim
Removing a Claim
Renaming a Claim
11.3.11. Configuring Timeouts
11.3.12. Minimal Configuration for Introspection
Specifying the Authorization Server
Startup Expectations
Runtime Expectations
11.3.13. Looking Up Attributes Post-Authentication
Looking Up Attributes Via SpEL
11.3.14. Overriding or Replacing Boot Auto Configuration
Using introspectionUri()
Using introspector()
Exposing a OpaqueTokenIntrospector @Bean
11.3.15. Configuring Authorization
Extracting Authorities Manually
11.3.16. Configuring Timeouts
11.3.17. Using Introspection with JWTs
11.3.18. Calling a /userinfo Endpoint
11.3.19. Bearer Token Resolution
Reading the Bearer Token from a Custom Header
Reading the Bearer Token from a Form Parameter
11.3.20. Bearer Token Propagation
RestTemplate support
12. SAML2
12.1. SAML 2.0 Login
12.1.1. SAML 2 Support in Spring Security
12.1.2. Saml 2 Login - High Level Concepts
12.1.3. Saml 2 Login - Current Feature Set
Saml 2 Login - Not Yet Supported
12.1.4. Saml 2 Login - Introduction to Java Configuration
Service Provider Metadata
Authentication Requests - SP Initiated Flow
12.1.5. Spring Boot 2.x Sample
Multiple Identity Provider Sample
13. Protection Against Exploits
13.1. Cross Site Request Forgery (CSRF)
13.1.1. CSRF Attacks
13.1.2. Synchronizer Token Pattern
13.1.3. When to use CSRF protection
CSRF protection and JSON
CSRF and Stateless Browser Applications
13.1.4. Using Spring Security CSRF Protection
Use proper HTTP verbs
Configure CSRF Protection
Include the CSRF Token
13.1.5. CSRF Caveats
Logging In
Logging Out
Multipart (file upload)
13.1.6. Overriding Defaults
13.2. Security HTTP Response Headers
13.2.1. Default Security Headers
13.2.2. Cache Control
13.2.3. Content Type Options
13.2.4. HTTP Strict Transport Security (HSTS)
13.2.5. HTTP Public Key Pinning (HPKP)
13.2.6. X-Frame-Options
13.2.7. X-XSS-Protection
13.2.8. Content Security Policy (CSP)
Configuring Content Security Policy
Additional Resources
13.2.9. Referrer Policy
Configuring Referrer Policy
13.2.10. Feature Policy
Configuring Feature Policy
13.2.11. Clear Site Data
Configuring Clear Site Data
13.2.12. Custom Headers
Static Headers
Headers Writer
13.3. HTTPS
13.3.1. Adding HTTP/HTTPS Channel Security
14. Integrations
14.1. Servlet API integration
14.1.1. Servlet 2.5+ Integration
14.1.2. Servlet 3+ Integration
Async Servlet Support
14.1.3. Servlet 3.1+ Integration
14.2. Spring Data Integration
14.2.1. Spring Data & Spring Security Configuration
14.2.2. Security Expressions within @Query
14.3. Concurrency Support
14.3.1. DelegatingSecurityContextRunnable
14.3.2. DelegatingSecurityContextExecutor
14.3.3. Spring Security Concurrency Classes
14.4. Jackson Support
14.5. Localization
14.6. Spring MVC Integration
14.6.1. @EnableWebMvcSecurity
14.6.2. MvcRequestMatcher
14.6.3. @AuthenticationPrincipal
14.6.4. Spring MVC Async Integration
14.6.5. Spring MVC and CSRF Integration
Automatic Token Inclusion
Resolving the CsrfToken
14.7. WebSocket Security
14.7.1. WebSocket Configuration
14.7.2. WebSocket Authentication
14.7.3. WebSocket Authorization
WebSocket Authorization Notes
Outbound Messages
14.7.4. Enforcing Same Origin Policy
Why Same Origin?
Spring WebSocket Allowed Origin
Adding CSRF to Stomp Headers
Disable CSRF within WebSockets
14.7.5. Working with SockJS
SockJS & frame-options
SockJS & Relaxing CSRF
14.8. CORS
14.9. JSP Tag Libraries
14.9.1. Declaring the Taglib
14.9.2. The authorize Tag
Disabling Tag Authorization for Testing
14.9.3. The authentication Tag
14.9.4. The accesscontrollist Tag
14.9.5. The csrfInput Tag
14.9.6. The csrfMetaTags Tag
15. Java Configuration
15.1. Hello Web Security Java Configuration
15.1.1. AbstractSecurityWebApplicationInitializer
15.1.2. AbstractSecurityWebApplicationInitializer without Existing Spring
15.1.3. AbstractSecurityWebApplicationInitializer with Spring MVC
15.2. HttpSecurity
15.3. Multiple HttpSecurity
15.4. Custom DSLs
15.5. Post Processing Configured Objects
16. Security Namespace Configuration
16.1. Introduction
16.1.1. Design of the Namespace
16.2. Getting Started with Security Namespace Configuration
16.2.1. web.xml Configuration
16.2.2. A Minimal <http> Configuration
Setting a Default Post-Login Destination
16.3. Advanced Web Features
16.3.1. Adding in Your Own Filters
16.4. Method Security
16.5. The Default AccessDecisionManager
16.5.1. Customizing the AccessDecisionManager
17. Testing
17.1. Testing Method Security
17.1.1. Security Test Setup
17.1.2. @WithMockUser
17.1.3. @WithAnonymousUser
17.1.4. @WithUserDetails
17.1.5. @WithSecurityContext
17.1.6. Test Meta Annotations
17.2. Spring MVC Test Integration
17.2.1. Setting Up MockMvc and Spring Security
17.2.2. SecurityMockMvcRequestPostProcessors
Testing with CSRF Protection
Running a Test as a User in Spring MVC Test
Running as a User in Spring MVC Test with RequestPostProcessor
Testing HTTP Basic Authentication
17.2.3. SecurityMockMvcRequestBuilders
Testing Form Based Authentication
Testing Bearer Authentication
Testing Logout
17.2.4. SecurityMockMvcResultMatchers
Unauthenticated Assertion
Authenticated Assertion
18. Spring Security Crypto Module
18.1. Introduction
18.2. Encryptors
18.2.1. BytesEncryptor
18.2.2. TextEncryptor
18.3. Key Generators
18.3.1. BytesKeyGenerator
18.3.2. StringKeyGenerator
18.4. Password Encoding
19. Appendix
19.1. Security Database Schema
19.1.1. User Schema
For Oracle database
Group Authorities
19.1.2. Persistent Login (Remember-Me) Schema
19.1.3. ACL Schema
MySQL and MariaDB
Microsoft SQL Server
Oracle Database
19.2. The Security Namespace
19.2.1. Web Application Security
<http-firewall> Element
<request-cache> Element
19.2.2. WebSocket Security
19.2.3. Authentication Services
19.2.4. Method Security
Securing Methods using
19.2.5. LDAP Namespace Options
Defining the LDAP Server using the
19.3. Spring Security Dependencies
19.3.1. spring-security-core
19.3.2. spring-security-remoting
19.3.3. spring-security-web
19.3.4. spring-security-ldap
19.3.5. spring-security-config
19.3.6. spring-security-acl
19.3.7. spring-security-cas
19.3.8. spring-security-openid
19.3.9. spring-security-taglibs
19.4. Proxy Server Configuration
19.5. Spring Security FAQ
19.5.1. General Questions
Will Spring Security take care of all my application security requirements?
Why not just use web.xml security?
What Java and Spring Framework versions are required?
I’m new to Spring Security and I need to build an application that supports CAS single sign-on over HTTPS, while allowing Basic authentication locally for certain URLs, authenticating against multiple back end user information sources (LDAP and JDBC). I’ve copied some configuration files I found but it doesn’t work.
19.5.2. Common Problems
When I try to log in, I get an error message that says "Bad Credentials". What’s wrong?
My application goes into an "endless loop" when I try to login, what’s going on?
I get an exception with the message "Access is denied (user is anonymous);". What’s wrong?
Why can I still see a secured page even after I’ve logged out of my application?
I get an exception with the message "An Authentication object was not found in the SecurityContext". What’s wrong?
I can’t get LDAP authentication to work.
Session Management
I’m using Spring Security’s concurrent session control to prevent users from logging in more than once at a time.
Why does the session Id change when I authenticate through Spring Security?
I’m using Tomcat (or some other servlet container) and have enabled HTTPS for my login page, switching back to HTTP afterwards.
I’m not switching between HTTP and HTTPS but my session is still getting lost
I’m trying to use the concurrent session-control support but it won’t let me log back in, even if I’m sure I’ve logged out and haven’t exceeded the allowed sessions.
Spring Security is creating a session somewhere, even though I’ve configured it not to, by setting the create-session attribute to never.
I get a 403 Forbidden when performing a POST
I’m forwarding a request to another URL using the RequestDispatcher, but my security constraints aren’t being applied.
I have added Spring Security’s <global-method-security> element to my application context but if I add security annotations to my Spring MVC controller beans (Struts actions etc.) then they don’t seem to have an effect.
I have a user who has definitely been authenticated, but when I try to access the SecurityContextHolder during some requests, the Authentication is null.
The authorize JSP Tag doesn’t respect my method security annotations when using the URL attribute.
19.5.3. Spring Security Architecture Questions
How do I know which package class X is in?
How do the namespace elements map to conventional bean configurations?
What does "ROLE_" mean and why do I need it on my role names?
How do I know which dependencies to add to my application to work with Spring Security?
What dependencies are needed to run an embedded ApacheDS LDAP server?
What is a UserDetailsService and do I need one?
19.5.4. Common "Howto" Requests
I need to login in with more information than just the username.
How do I apply different intercept-url constraints where only the fragment value of the requested URLs differs (e.g./foo#bar and /foo#blah?
How do I access the user’s IP Address (or other web-request data) in a UserDetailsService?
How do I access the HttpSession from a UserDetailsService?
How do I access the user’s password in a UserDetailsService?
How do I define the secured URLs within an application dynamically?
How do I authenticate against LDAP but load user roles from a database?
I want to modify the property of a bean that is created by the namespace, but there is nothing in the schema to support it.
III. Reactive Applications
20. WebFlux Security
20.1. Minimal WebFlux Security Configuration
20.2. Explicit WebFlux Security Configuration
21. Default Security Headers
21.1. Cache Control
21.2. Content Type Options
21.3. HTTP Strict Transport Security (HSTS)
21.4. X-Frame-Options
21.5. X-XSS-Protection
21.6. Content Security Policy (CSP)
21.6.1. Configuring Content Security Policy
21.6.2. Additional Resources
21.7. Referrer Policy
21.7.1. Configuring Referrer Policy
21.8. Feature Policy
21.8.1. Configuring Feature Policy
21.9. Clear Site Data
21.9.1. Configuring Clear Site Data
22. Redirect to HTTPS
23. OAuth2 WebFlux
23.1. OAuth 2.0 Login
23.1.1. Spring Boot 2.0 Sample
Initial setup
Setting the redirect URI
Configure application.yml
Boot up the application
23.1.2. Using OpenID Provider Configuration
23.1.3. Explicit OAuth2 Login Configuration
23.2. OAuth2 Client
23.3. OAuth 2.0 Resource Server
23.3.1. Dependencies
23.3.2. Minimal Configuration for JWTs
Specifying the Authorization Server
Startup Expectations
Runtime Expectations
Specifying the Authorization Server JWK Set Uri Directly
Overriding or Replacing Boot Auto Configuration
23.3.3. Configuring Trusted Algorithms
Via Spring Boot
Using a Builder
Trusting a Single Asymmetric Key
Trusting a Single Symmetric Key
Configuring Authorization
Configuring Validation
Minimal Configuration for Introspection
Looking Up Attributes Post-Authentication
Overriding or Replacing Boot Auto Configuration
Configuring Authorization
Using Introspection with JWTs
Calling a /userinfo Endpoint
23.3.4. Bearer Token Propagation
24. @RegisteredOAuth2AuthorizedClient
25. Reactive X.509 Authentication
26. WebClient
26.1. WebClient OAuth2 Setup
26.2. Implicit OAuth2AuthorizedClient
26.3. Explicit OAuth2AuthorizedClient
26.4. clientRegistrationId
27. EnableReactiveMethodSecurity
28. Reactive Test Support
28.1. Testing Reactive Method Security
28.2. WebTestClientSupport
28.2.1. Authentication
28.2.2. CSRF Support
28.2.3. Testing Bearer Authentication
mockJwt() WebTestClientConfigurer
authentication() WebTestClientConfigurer
29. RSocket Security
29.1. Minimal RSocket Security Configuration
29.2. Adding SecuritySocketAcceptorInterceptor
29.3. RSocket Authentication
29.3.1. Authentication at Setup vs Request Time
29.3.2. Basic Authentication
29.3.3. JWT
29.4. RSocket Authorization