Spring Security Reference

Authors

Ben Alex , Luke Taylor , Rob Winch , Gunnar Hillert , Joe Grandja , Jay Bryant

5.2.0-gh2567

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. About
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.1
3.1. Servlet
3.2. WebFlux
3.3. Integrations
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. ACL — spring-security-acl.jar
5.10. CAS — spring-security-cas.jar
5.11. OpenID — spring-security-openid.jar
5.12. 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. Servlet Architecture Overview
8.1. Servlet Architecture Overview
8.1.1. Understanding the Servlet Filter API
8.1.2. Registering a Servlet Filter
8.1.3. Dispatch Types
8.1.4. Filter Ordering
8.1.5. Using DelegatingFilterProxy
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
BindAuthenticator
PasswordComparisonAuthenticator
9.5.2. Connecting to the LDAP Server
9.5.3. LDAP Search Objects
FilterBasedLdapUserSearch
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.6.2. LDAP Java Configuration
9.7. AuthenticationProvider
9.7.1. AuthenticationProvider Java Configuration
9.7.2. AuthenticationProvider XML Configuration
9.8. UserDetailsService
9.9. PasswordEncoder
9.9.1. Password History
9.9.2. DelegatingPasswordEncoder
Password Storage Format
Password Encoding
Password Matching
Getting Started Experience
Troubleshooting
9.9.3. BCryptPasswordEncoder
9.9.4. Pbkdf2PasswordEncoder
9.9.5. SCryptPasswordEncoder
9.9.6. Other PasswordEncoders
9.9.7. PasswordEncoder XML Configuration
9.10. The Authentication Manager and the Namespace
9.11. Session Management
9.11.1. Detecting Timeouts
9.11.2. Concurrent Session Control
9.11.3. Session Fixation Attack Protection
9.11.4. SessionManagementFilter
9.11.5. SessionAuthenticationStrategy
9.11.6. Concurrency Control
Querying the SessionRegistry for currently authenticated users and their sessions
9.12. Remember-Me Authentication
9.12.1. Overview
9.12.2. Simple Hash-Based Token Approach
9.12.3. Persistent Token Approach
9.12.4. Remember-Me Interfaces and Implementations
TokenBasedRememberMeServices
PersistentTokenBasedRememberMeServices
9.13. OpenID Support
9.13.1. Attribute Exchange
9.14. Anonymous Authentication
9.14.1. Overview
9.14.2. Configuration
9.14.3. AuthenticationTrustResolver
9.15. Pre-Authentication Scenarios
9.15.1. Pre-Authentication Framework Classes
AbstractPreAuthenticatedProcessingFilter
PreAuthenticatedAuthenticationProvider
Http403ForbiddenEntryPoint
9.15.2. Concrete Implementations
Request-Header Authentication (Siteminder)
Java EE Container Authentication
9.16. Java Authentication and Authorization Service (JAAS) Provider
9.16.1. Overview
9.16.2. AbstractJaasAuthenticationProvider
JAAS CallbackHandler
JAAS AuthorityGranter
9.16.3. DefaultJaasAuthenticationProvider
InMemoryConfiguration
DefaultJaasAuthenticationProvider Example Configuration
9.16.4. JaasAuthenticationProvider
9.16.5. Running as a Subject
9.17. CAS Authentication
9.17.1. Overview
9.17.2. How CAS Works
Spring Security and CAS Interaction Sequence
9.17.3. Configuration of CAS Client
Service Ticket Authentication
Single Logout
Authenticating to a Stateless Service with CAS
Proxy Ticket Authentication
9.18. X.509 Authentication
9.18.1. Overview
9.18.2. Adding X.509 Authentication to Your Web Application
9.18.3. Setting up SSL in Tomcat
9.19. Run-As Authentication Replacement
9.19.1. Overview
9.19.2. Configuration
9.20. Form Login
9.20.1. Form Login Java Configuration
9.20.2. Form Login XML Configuration
Form and Basic Login Options
9.21. Basic Authentication
9.21.1. BasicAuthenticationFilter
9.21.2. Configuration
9.22. DigestAuthenticationFilter
9.22.1. Configuration
9.23. Handling Logouts
9.23.1. Logout Java Configuration
9.23.2. Logout XML Configuration
9.23.3. LogoutHandler
9.23.4. LogoutSuccessHandler
9.23.5. Further Logout-Related References
9.24. 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.0 Sample
Initial setup
Setting the redirect URI
Configure application.yml
Boot up the application
11.1.2. ClientRegistration
11.1.3. Spring Boot 2.0 Property Mappings
11.1.4. ClientRegistrationRepository
11.1.5. CommonOAuth2Provider
11.1.6. Configuring Custom Provider Properties
11.1.7. Overriding Spring Boot 2.0 Auto-configuration
Register a ClientRegistrationRepository @Bean
Provide a WebSecurityConfigurerAdapter
Completely Override the Auto-configuration
11.1.8. Java Configuration without Spring Boot 2.0
11.1.9. OAuth2AuthorizedClient / OAuth2AuthorizedClientService
11.1.10. OAuth 2.0 Login — Advanced Configuration
OAuth 2.0 Login Page
Authorization Endpoint
Redirection Endpoint
Token Endpoint
UserInfo Endpoint
11.1.11. Additional Resources
11.2. WebClient OAuth2 for Servlet Environments
11.2.1. WebClient OAuth2 Setup
11.2.2. Implicit OAuth2AuthorizedClient
11.2.3. Explicit OAuth2AuthorizedClient
11.2.4. clientRegistrationId
12. Protection Against Exploits
12.1. Cross Site Request Forgery (CSRF)
12.1.1. CSRF Attacks
12.1.2. Synchronizer Token Pattern
12.1.3. When to use CSRF protection
CSRF protection and JSON
CSRF and Stateless Browser Applications
12.1.4. Using Spring Security CSRF Protection
Use proper HTTP verbs
Configure CSRF Protection
Include the CSRF Token
12.1.5. CSRF Caveats
Timeouts
Logging In
Logging Out
Multipart (file upload)
HiddenHttpMethodFilter
12.1.6. Overriding Defaults
12.2. Security HTTP Response Headers
12.2.1. Default Security Headers
12.2.2. Cache Control
12.2.3. Content Type Options
12.2.4. HTTP Strict Transport Security (HSTS)
12.2.5. HTTP Public Key Pinning (HPKP)
12.2.6. X-Frame-Options
12.2.7. X-XSS-Protection
12.2.8. Content Security Policy (CSP)
Configuring Content Security Policy
Additional Resources
12.2.9. Referrer Policy
Configuring Referrer Policy
12.2.10. Feature Policy
Configuring Feature Policy
12.2.11. Custom Headers
Static Headers
Headers Writer
DelegatingRequestMatcherHeaderWriter
12.3. HTTPS
12.3.1. Adding HTTP/HTTPS Channel Security
13. Integrations
13.1. Servlet API integration
13.1.1. Servlet 2.5+ Integration
HttpServletRequest.getRemoteUser()
HttpServletRequest.getUserPrincipal()
HttpServletRequest.isUserInRole(String)
13.1.2. Servlet 3+ Integration
HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)
HttpServletRequest.login(String,String)
HttpServletRequest.logout()
AsyncContext.start(Runnable)
Async Servlet Support
13.1.3. Servlet 3.1+ Integration
HttpServletRequest#changeSessionId()
13.2. Spring Data Integration
13.2.1. Spring Data & Spring Security Configuration
13.2.2. Security Expressions within @Query
13.3. Concurrency Support
13.3.1. DelegatingSecurityContextRunnable
13.3.2. DelegatingSecurityContextExecutor
13.3.3. Spring Security Concurrency Classes
13.4. Jackson Support
13.5. Localization
13.6. Spring MVC Integration
13.6.1. @EnableWebMvcSecurity
13.6.2. MvcRequestMatcher
13.6.3. @AuthenticationPrincipal
13.6.4. Spring MVC Async Integration
13.6.5. Spring MVC and CSRF Integration
Automatic Token Inclusion
Resolving the CsrfToken
13.7. WebSocket Security
13.7.1. WebSocket Configuration
13.7.2. WebSocket Authentication
13.7.3. WebSocket Authorization
WebSocket Authorization Notes
Outbound Messages
13.7.4. Enforcing Same Origin Policy
Why Same Origin?
Spring WebSocket Allowed Origin
Adding CSRF to Stomp Headers
Disable CSRF within WebSockets
13.7.5. Working with SockJS
SockJS & frame-options
SockJS & Relaxing CSRF
13.8. CORS
13.9. JSP Tag Libraries
13.9.1. Declaring the Taglib
13.9.2. The authorize Tag
Disabling Tag Authorization for Testing
13.9.3. The authentication Tag
13.9.4. The accesscontrollist Tag
13.9.5. The csrfInput Tag
13.9.6. The csrfMetaTags Tag
14. Java Configuration
14.1. HttpSecurity
14.2. Multiple HttpSecurity
14.3. Custom DSLs
14.4. Post Processing Configured Objects
14.5. Advanced Web Features
14.5.1. Adding in Your Own Filters
15. Testing
15.1. Testing Method Security
15.1.1. Security Test Setup
15.1.2. @WithMockUser
15.1.3. @WithAnonymousUser
15.1.4. @WithUserDetails
15.1.5. @WithSecurityContext
15.1.6. Test Meta Annotations
15.2. Spring MVC Test Integration
15.2.1. Setting Up MockMvc and Spring Security
15.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
15.2.3. SecurityMockMvcRequestBuilders
Testing Form Based Authentication
Testing Logout
15.2.4. SecurityMockMvcResultMatchers
Unauthenticated Assertion
Authenticated Assertion
16. Spring Security Crypto Module
16.1. Introduction
16.2. Encryptors
16.2.1. BytesEncryptor
16.2.2. TextEncryptor
16.3. Key Generators
16.3.1. BytesKeyGenerator
16.3.2. StringKeyGenerator
16.4. Password Encoding
17. Appendix
17.1. Security Database Schema
17.1.1. User Schema
For Oracle database
Group Authorities
17.1.2. Persistent Login (Remember-Me) Schema
17.1.3. ACL Schema
HyperSQL
PostgreSQL
MySQL and MariaDB
Microsoft SQL Server
Oracle Database
17.2. The Security Namespace
17.2.1. Web Application Security
<debug>
<http>
<access-denied-handler>
<cors>
<headers>
<cache-control>
<hsts>
<hpkp>
<pins>
<pin>
<content-security-policy>
<referrer-policy>
<feature-policy>
<frame-options>
<xss-protection>
<content-type-options>
<header>
<anonymous>
<csrf>
<custom-filter>
<expression-handler>
<form-login>
<http-basic>
<http-firewall> Element
<intercept-url>
<jee>
<logout>
<openid-login>
<attribute-exchange>
<openid-attribute>
<port-mappings>
<port-mapping>
<remember-me>
<request-cache> Element
<session-management>
<concurrency-control>
<x509>
<filter-chain-map>
<filter-chain>
<filter-security-metadata-source>
17.2.2. WebSocket Security
<websocket-message-broker>
<intercept-message>
17.2.3. Authentication Services
<authentication-manager>
<authentication-provider>
<jdbc-user-service>
<password-encoder>
<user-service>
<user>
17.2.4. Method Security
<global-method-security>
<after-invocation-provider>
<pre-post-annotation-handling>
<invocation-attribute-factory>
<post-invocation-advice>
<pre-invocation-advice>
Securing Methods using
<intercept-methods>
<method-security-metadata-source>
<protect>
17.2.5. LDAP Namespace Options
Defining the LDAP Server using the
<ldap-authentication-provider>
<password-compare>
<ldap-user-service>
17.3. Spring Security Dependencies
17.3.1. spring-security-core
17.3.2. spring-security-remoting
17.3.3. spring-security-web
17.3.4. spring-security-ldap
17.3.5. spring-security-config
17.3.6. spring-security-acl
17.3.7. spring-security-cas
17.3.8. spring-security-openid
17.3.9. spring-security-taglibs
17.4. Proxy Server Configuration
17.5. Spring Security FAQ
17.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.
17.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.
17.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?
17.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
18. WebFlux Security
18.1. Minimal WebFlux Security Configuration
18.2. Explicit WebFlux Security Configuration
19. Default Security Headers
19.1. Cache Control
19.2. Content Type Options
19.3. HTTP Strict Transport Security (HSTS)
19.4. X-Frame-Options
19.5. X-XSS-Protection
19.6. Content Security Policy (CSP)
19.6.1. Configuring Content Security Policy
19.6.2. Additional Resources
19.7. Referrer Policy
19.7.1. Configuring Referrer Policy
19.8. Feature Policy
19.8.1. Configuring Feature Policy
20. Redirect to HTTPS
21. OAuth2 WebFlux
21.1. OAuth 2.0 Login
21.1.1. Spring Boot 2.0 Sample
Initial setup
Setting the redirect URI
Configure application.yml
Boot up the application
21.1.2. Using OpenID Provider Configuration
21.1.3. Explicit OAuth2 Login Configuration
21.2. OAuth2 Client
21.3. OAuth2 Resource Server
22. @RegisteredOAuth2AuthorizedClient
23. WebClient
23.1. WebClient OAuth2 Setup
23.2. Implicit OAuth2AuthorizedClient
23.3. Explicit OAuth2AuthorizedClient
23.4. clientRegistrationId
24. EnableReactiveMethodSecurity
25. Reactive Test Support
25.1. Testing Reactive Method Security
25.2. WebTestClientSupport
25.2.1. Authentication
25.2.2. CSRF Support