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. Features
5.1. Protection Against Exploits
5.1.1. Cross Site Request Forgery (CSRF)
What is a CSRF Attack?
Protecting Against CSRF Attacks
When to use CSRF protection
CSRF Considerations
5.1.2. Security HTTP Response Headers
Default Security Headers
Cache Control
Content Type Options
HTTP Strict Transport Security (HSTS)
HTTP Public Key Pinning (HPKP)
Content Security Policy (CSP)
Referrer Policy
Feature Policy
Clear Site Data
Custom Headers
5.1.3. HTTP
Redirect to HTTPS
Strict Transport Security
Proxy Server Configuration
6. Project Modules
6.1. Core — spring-security-core.jar
6.2. Remoting — spring-security-remoting.jar
6.3. Web — spring-security-web.jar
6.4. Config — spring-security-config.jar
6.5. LDAP — spring-security-ldap.jar
6.6. OAuth 2.0 Core — spring-security-oauth2-core.jar
6.7. OAuth 2.0 Client — spring-security-oauth2-client.jar
6.8. OAuth 2.0 JOSE — spring-security-oauth2-jose.jar
6.9. OAuth 2.0 Resource Server — spring-security-oauth2-resource-server.jar
6.10. ACL — spring-security-acl.jar
6.11. CAS — spring-security-cas.jar
6.12. OpenID — spring-security-openid.jar
6.13. Test — spring-security-test.jar
7. Samples
II. Servlet Applications
8. Hello Spring Security
8.1. Updating Dependencies
8.2. Starting Hello Spring Security Boot
8.3. Spring Boot Auto Configuration
9. Architecture and Implementation
9.1. Technical Overview
9.1.1. Runtime Environment
9.1.2. Core Components
SecurityContextHolder, SecurityContext and Authentication Objects
The UserDetailsService
9.1.3. Authentication
What is authentication in Spring Security?
Setting the SecurityContextHolder Contents Directly
9.1.4. Authentication in a Web Application
Authentication Mechanism
Storing the SecurityContext between requests
9.1.5. Access-Control (Authorization) in Spring Security
Security and AOP Advice
Secure Objects and the AbstractSecurityInterceptor
9.2. Core Services
9.2.1. The AuthenticationManager, ProviderManager and AuthenticationProvider
Erasing Credentials on Successful Authentication
9.2.2. UserDetailsService Implementations
In-Memory Authentication
10. Authentication
10.1. In-Memory Authentication
10.2. JDBC Authentication
10.3. LDAP Authentication
10.3.1. Overview
10.3.2. Using LDAP with Spring Security
10.4. Configuring an LDAP Server
10.4.1. Using an Embedded Test Server
10.4.2. Using Bind Authentication
10.4.3. Loading Authorities
10.5. Implementation Classes
10.5.1. LdapAuthenticator Implementations
Common Functionality
10.5.2. Connecting to the LDAP Server
10.5.3. LDAP Search Objects
10.5.4. LdapAuthoritiesPopulator
10.5.5. Spring Bean Configuration
10.5.6. LDAP Attributes and Customized UserDetails
10.6. Active Directory Authentication
10.6.1. ActiveDirectoryLdapAuthenticationProvider
Active Directory Error Codes
10.7. LDAP Java Configuration
10.8. AuthenticationProvider
10.8.1. AuthenticationProvider Java Configuration
10.8.2. AuthenticationProvider XML Configuration
10.9. UserDetailsService
10.10. Password Encoding
10.10.1. Password History
10.10.2. DelegatingPasswordEncoder
Password Storage Format
Password Encoding
Password Matching
Getting Started Experience
10.10.3. BCryptPasswordEncoder
10.10.4. Argon2PasswordEncoder
10.10.5. Pbkdf2PasswordEncoder
10.10.6. SCryptPasswordEncoder
10.10.7. Other PasswordEncoders
10.10.8. Password Encoder XML Configuration
10.11. The Authentication Manager and the Namespace
10.12. Session Management
10.12.1. Detecting Timeouts
10.12.2. Concurrent Session Control
10.12.3. Session Fixation Attack Protection
10.12.4. SessionManagementFilter
10.12.5. SessionAuthenticationStrategy
10.12.6. Concurrency Control
Querying the SessionRegistry for currently authenticated users and their sessions
10.13. Remember-Me Authentication
10.13.1. Overview
10.13.2. Simple Hash-Based Token Approach
10.13.3. Persistent Token Approach
10.13.4. Remember-Me Interfaces and Implementations
10.14. OpenID Support
10.14.1. Attribute Exchange
10.15. Anonymous Authentication
10.15.1. Overview
10.15.2. Configuration
10.15.3. AuthenticationTrustResolver
10.15.4. Getting Anonymous Authentications with Spring MVC
10.16. Pre-Authentication Scenarios
10.16.1. Pre-Authentication Framework Classes
10.16.2. Concrete Implementations
Request-Header Authentication (Siteminder)
Java EE Container Authentication
10.17. Java Authentication and Authorization Service (JAAS) Provider
10.17.1. Overview
10.17.2. AbstractJaasAuthenticationProvider
JAAS CallbackHandler
JAAS AuthorityGranter
10.17.3. DefaultJaasAuthenticationProvider
DefaultJaasAuthenticationProvider Example Configuration
10.17.4. JaasAuthenticationProvider
10.17.5. Running as a Subject
10.18. CAS Authentication
10.18.1. Overview
10.18.2. How CAS Works
Spring Security and CAS Interaction Sequence
10.18.3. Configuration of CAS Client
Service Ticket Authentication
Single Logout
Authenticating to a Stateless Service with CAS
Proxy Ticket Authentication
10.19. X.509 Authentication
10.19.1. Overview
10.19.2. Adding X.509 Authentication to Your Web Application
10.19.3. Setting up SSL in Tomcat
10.20. Run-As Authentication Replacement
10.20.1. Overview
10.20.2. Configuration
10.21. Form Login
10.21.1. Form Login Java Configuration
10.21.2. Form Login XML Configuration
Form and Basic Login Options
10.22. Basic and Digest Authentication
10.22.1. BasicAuthenticationFilter
10.22.2. Configuration
10.23. DigestAuthenticationFilter
10.23.1. Configuration
10.24. Handling Logouts
10.24.1. Logout Java Configuration
10.24.2. Logout XML Configuration
10.24.3. LogoutHandler
10.24.4. LogoutSuccessHandler
10.24.5. Further Logout-Related References
10.25. Setting a Custom AuthenticationEntryPoint
11. Authorization
11.1. Authorization Architecture
11.1.1. Authorities
11.1.2. Pre-Invocation Handling
The AccessDecisionManager
Voting-Based AccessDecisionManager Implementations
11.1.3. After Invocation Handling
11.1.4. Hierarchical Roles
11.2. Secure Object Implementations
11.2.1. AOP Alliance (MethodInvocation) Security Interceptor
Explicit MethodSecurityInterceptor Configuration
11.2.2. AspectJ (JoinPoint) Security Interceptor
11.3. Expression-Based Access Control
11.3.1. Overview
Common Built-In Expressions
11.3.2. Web Security Expressions
Referring to Beans in Web Security Expressions
Path Variables in Web Security Expressions
11.3.3. Method Security Expressions
@Pre and @Post Annotations
Built-In Expressions
11.4. Authorize Requests
11.5. Method Security
11.5.1. EnableGlobalMethodSecurity
11.5.2. GlobalMethodSecurityConfiguration
11.5.3. The <global-method-security> Element
11.5.4. Adding Security Pointcuts using protect-pointcut
11.6. Domain Object Security (ACLs)
11.6.1. Overview
11.6.2. Key Concepts
11.6.3. Getting Started
12. OAuth2
12.1. OAuth 2.0 Login
12.1.1. Spring Boot 2.x Sample
Initial setup
Setting the redirect URI
Configure application.yml
Boot up the application
12.1.2. Spring Boot 2.x Property Mappings
12.1.3. CommonOAuth2Provider
12.1.4. Configuring Custom Provider Properties
12.1.5. Overriding Spring Boot 2.x Auto-configuration
Register a ClientRegistrationRepository @Bean
Provide a WebSecurityConfigurerAdapter
Completely Override the Auto-configuration
12.1.6. Java Configuration without Spring Boot 2.x
12.1.7. Advanced Configuration
OAuth 2.0 Login Page
Redirection Endpoint
UserInfo Endpoint
ID Token Signature Verification
OpenID Connect 1.0 Logout
12.2. OAuth 2.0 Client
12.2.1. Core Interfaces / Classes
OAuth2AuthorizedClientRepository / OAuth2AuthorizedClientService
OAuth2AuthorizedClientManager / OAuth2AuthorizedClientProvider
12.2.2. Authorization Grant Support
Authorization Code
Refresh Token
Client Credentials
Resource Owner Password Credentials
12.2.3. Additional Features
Resolving an Authorized Client
12.2.4. WebClient integration for Servlet Environments
Providing the Authorized Client
Defaulting the Authorized Client
12.3. OAuth 2.0 Resource Server
12.3.1. Dependencies
12.3.2. Minimal Configuration for JWTs
Specifying the Authorization Server
Startup Expectations
Runtime Expectations
12.3.3. Specifying the Authorization Server JWK Set Uri Directly
12.3.4. Overriding or Replacing Boot Auto Configuration
Using jwkSetUri()
Using decoder()
Exposing a JwtDecoder @Bean
12.3.5. Configuring Trusted Algorithms
Via Spring Boot
Using a Builder
From JWK Set response
12.3.6. Trusting a Single Asymmetric Key
Via Spring Boot
Using a Builder
12.3.7. Trusting a Single Symmetric Key
12.3.8. Configuring Authorization
Extracting Authorities Manually
12.3.9. Configuring Validation
Customizing Timestamp Validation
Configuring a Custom Validator
12.3.10. Configuring Claim Set Mapping
Customizing the Conversion of a Single Claim
Adding a Claim
Removing a Claim
Renaming a Claim
12.3.11. Configuring Timeouts
12.3.12. Minimal Configuration for Introspection
Specifying the Authorization Server
Startup Expectations
Runtime Expectations
12.3.13. Looking Up Attributes Post-Authentication
Looking Up Attributes Via SpEL
12.3.14. Overriding or Replacing Boot Auto Configuration
Using introspectionUri()
Using introspector()
Exposing a OpaqueTokenIntrospector @Bean
12.3.15. Configuring Authorization
Extracting Authorities Manually
12.3.16. Configuring Timeouts
12.3.17. Using Introspection with JWTs
12.3.18. Calling a /userinfo Endpoint
12.3.19. Supporting both JWT and Opaque Token
12.3.20. Multi-tenancy
Resolving the Tenant By Request Material
Resolving the Tenant By Claim
Parsing the Claim Only Once
12.3.21. Bearer Token Resolution
Reading the Bearer Token from a Custom Header
Reading the Bearer Token from a Form Parameter
12.3.22. Bearer Token Propagation
RestTemplate support
13. SAML2
13.1. SAML 2.0 Login
13.1.1. SAML 2 Support in Spring Security
13.1.2. Saml 2 Login - High Level Concepts
13.1.3. Saml 2 Login - Current Feature Set
Saml 2 Login - Not Yet Supported
13.1.4. Saml 2 Login - Introduction to Java Configuration
Service Provider Metadata
Authentication Requests - SP Initiated Flow
13.1.5. Spring Boot 2.x Sample
Multiple Identity Provider Sample
14. Protection Against Exploits
14.1. Cross Site Request Forgery (CSRF) for Servlet Environments
14.1.1. Using Spring Security CSRF Protection
Use proper HTTP verbs
Configure CSRF Protection
Include the CSRF Token
14.1.2. CSRF Considerations
Logging In
Logging Out
CSRF and Session Timeouts
Multipart (file upload)
14.2. Security HTTP Response Headers
14.2.1. Default Security Headers
14.2.2. Cache Control
14.2.3. Content Type Options
14.2.4. HTTP Strict Transport Security (HSTS)
14.2.5. HTTP Public Key Pinning (HPKP)
14.2.6. X-Frame-Options
14.2.7. X-XSS-Protection
14.2.8. Content Security Policy (CSP)
14.2.9. Referrer Policy
14.2.10. Feature Policy
14.2.11. Clear Site Data
14.2.12. Custom Headers
Static Headers
Headers Writer
14.3. HTTP
14.3.1. Redirect to HTTPS
14.3.2. Strict Transport Security
14.3.3. Proxy Server Configuration
15. Integrations
15.1. Servlet API integration
15.1.1. Servlet 2.5+ Integration
15.1.2. Servlet 3+ Integration
Async Servlet Support
15.1.3. Servlet 3.1+ Integration
15.2. Spring Data Integration
15.2.1. Spring Data & Spring Security Configuration
15.2.2. Security Expressions within @Query
15.3. Concurrency Support
15.3.1. DelegatingSecurityContextRunnable
15.3.2. DelegatingSecurityContextExecutor
15.3.3. Spring Security Concurrency Classes
15.4. Jackson Support
15.5. Localization
15.6. Spring MVC Integration
15.6.1. @EnableWebMvcSecurity
15.6.2. MvcRequestMatcher
15.6.3. @AuthenticationPrincipal
15.6.4. Spring MVC Async Integration
15.6.5. Spring MVC and CSRF Integration
Automatic Token Inclusion
Resolving the CsrfToken
15.7. WebSocket Security
15.7.1. WebSocket Configuration
15.7.2. WebSocket Authentication
15.7.3. WebSocket Authorization
WebSocket Authorization Notes
Outbound Messages
15.7.4. Enforcing Same Origin Policy
Why Same Origin?
Spring WebSocket Allowed Origin
Adding CSRF to Stomp Headers
Disable CSRF within WebSockets
15.7.5. Working with SockJS
SockJS & frame-options
SockJS & Relaxing CSRF
15.8. CORS
15.9. JSP Tag Libraries
15.9.1. Declaring the Taglib
15.9.2. The authorize Tag
Disabling Tag Authorization for Testing
15.9.3. The authentication Tag
15.9.4. The accesscontrollist Tag
15.9.5. The csrfInput Tag
15.9.6. The csrfMetaTags Tag
16. Java Configuration
16.1. Hello Web Security Java Configuration
16.1.1. AbstractSecurityWebApplicationInitializer
16.1.2. AbstractSecurityWebApplicationInitializer without Existing Spring
16.1.3. AbstractSecurityWebApplicationInitializer with Spring MVC
16.2. HttpSecurity
16.3. Multiple HttpSecurity
16.4. Custom DSLs
16.5. Post Processing Configured Objects
17. Security Namespace Configuration
17.1. Introduction
17.1.1. Design of the Namespace
17.2. Getting Started with Security Namespace Configuration
17.2.1. web.xml Configuration
17.2.2. A Minimal <http> Configuration
Setting a Default Post-Login Destination
17.3. Advanced Web Features
17.3.1. Adding in Your Own Filters
17.4. Method Security
17.5. The Default AccessDecisionManager
17.5.1. Customizing the AccessDecisionManager
18. Testing
18.1. Testing Method Security
18.1.1. Security Test Setup
18.1.2. @WithMockUser
18.1.3. @WithAnonymousUser
18.1.4. @WithUserDetails
18.1.5. @WithSecurityContext
18.1.6. Test Meta Annotations
18.2. Spring MVC Test Integration
18.2.1. Setting Up MockMvc and Spring Security
18.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
18.2.3. SecurityMockMvcRequestBuilders
Testing Form Based Authentication
Testing Bearer Authentication
Testing Logout
18.2.4. SecurityMockMvcResultMatchers
Unauthenticated Assertion
Authenticated Assertion
19. Spring Security Crypto Module
19.1. Introduction
19.2. Encryptors
19.2.1. BytesEncryptor
19.2.2. TextEncryptor
19.3. Key Generators
19.3.1. BytesKeyGenerator
19.3.2. StringKeyGenerator
19.4. Password Encoding
20. Appendix
20.1. Security Database Schema
20.1.1. User Schema
For Oracle database
Group Authorities
20.1.2. Persistent Login (Remember-Me) Schema
20.1.3. ACL Schema
MySQL and MariaDB
Microsoft SQL Server
Oracle Database
20.2. The Security Namespace
20.2.1. Web Application Security
<http-firewall> Element
<request-cache> Element
20.2.2. WebSocket Security
20.2.3. Authentication Services
20.2.4. Method Security
Securing Methods using
20.2.5. LDAP Namespace Options
Defining the LDAP Server using the
20.3. Spring Security Dependencies
20.3.1. spring-security-core
20.3.2. spring-security-remoting
20.3.3. spring-security-web
20.3.4. spring-security-ldap
20.3.5. spring-security-config
20.3.6. spring-security-acl
20.3.7. spring-security-cas
20.3.8. spring-security-openid
20.3.9. spring-security-taglibs
20.4. Spring Security FAQ
20.4.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.
20.4.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.
20.4.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?
20.4.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
21. WebFlux Security
21.1. Minimal WebFlux Security Configuration
21.2. Explicit WebFlux Security Configuration
22. Protection Against Exploits
22.1. Cross Site Request Forgery (CSRF) for WebFlux Environments
22.1.1. Using Spring Security CSRF Protection
Use proper HTTP verbs
Configure CSRF Protection
Include the CSRF Token
22.1.2. CSRF Considerations
Logging In
Logging Out
CSRF and Session Timeouts
Multipart (file upload)
22.2. Security HTTP Response Headers
22.2.1. Default Security Headers
22.2.2. Cache Control
22.2.3. Content Type Options
22.2.4. HTTP Strict Transport Security (HSTS)
22.2.5. X-Frame-Options
22.2.6. X-XSS-Protection
22.2.7. Content Security Policy (CSP)
22.2.8. Referrer Policy
22.2.9. Feature Policy
22.2.10. Clear Site Data
22.3. HTTP
22.3.1. Redirect to HTTPS
22.3.2. Strict Transport Security
22.3.3. Proxy Server Configuration
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