Spring Security Reference

Authors

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

5.1.5.RELEASE

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. Spring Security Community
1.1. Getting Help
1.2. Becoming Involved
1.3. Source Code
1.4. Apache 2 License
1.5. Social Media
2. What’s New in Spring Security 5.1
2.1. Servlet
2.2. WebFlux
2.3. Integrations
3. Getting Spring Security
3.1. Release Numbering
3.2. Usage with Maven
3.2.1. Spring Boot with Maven
3.2.2. Maven Without Spring Boot
3.2.3. Maven Repositories
3.3. Gradle
3.3.1. Spring Boot with Gradle
3.3.2. Gradle Without Spring Boot
3.3.3. Gradle Repositories
4. Project Modules
4.1. Core - spring-security-core.jar
4.2. Remoting - spring-security-remoting.jar
4.3. Web - spring-security-web.jar
4.4. Config - spring-security-config.jar
4.5. LDAP - spring-security-ldap.jar
4.6. OAuth 2.0 Core - spring-security-oauth2-core.jar
4.7. OAuth 2.0 Client - spring-security-oauth2-client.jar
4.8. OAuth 2.0 JOSE - spring-security-oauth2-jose.jar
4.9. ACL - spring-security-acl.jar
4.10. CAS - spring-security-cas.jar
4.11. OpenID - spring-security-openid.jar
4.12. Test - spring-security-test.jar
5. Sample Applications
5.1. Tutorial Sample
5.2. Contacts
5.3. LDAP Sample
5.4. OpenID Sample
5.5. CAS Sample
5.6. JAAS Sample
5.7. Pre-Authentication Sample
II. Servlet Applications
6. Java Configuration
6.1. Hello Web Security Java Configuration
6.1.1. AbstractSecurityWebApplicationInitializer
6.1.2. AbstractSecurityWebApplicationInitializer without Existing Spring
6.1.3. AbstractSecurityWebApplicationInitializer with Spring MVC
6.2. HttpSecurity
6.3. Java Configuration and Form Login
6.4. Authorize Requests
6.5. Handling Logouts
6.5.1. LogoutHandler
6.5.2. LogoutSuccessHandler
6.5.3. Further Logout-Related References
6.6. OAuth 2.0 Client
6.6.1. ClientRegistration
6.6.2. ClientRegistrationRepository
6.6.3. OAuth2AuthorizedClient
6.6.4. OAuth2AuthorizedClientRepository / OAuth2AuthorizedClientService
6.6.5. RegisteredOAuth2AuthorizedClient
6.6.6. AuthorizationRequestRepository
6.6.7. OAuth2AuthorizationRequestResolver
6.6.8. OAuth2AccessTokenResponseClient
6.7. OAuth 2.0 Login
6.7.1. Spring Boot 2.x Sample
Initial setup
Setting the redirect URI
Configure application.yml
Boot up the application
6.7.2. Spring Boot 2.x Property Mappings
6.7.3. CommonOAuth2Provider
6.7.4. Configuring Custom Provider Properties
6.7.5. Overriding Spring Boot 2.x Auto-configuration
Register a ClientRegistrationRepository @Bean
Provide a WebSecurityConfigurerAdapter
Completely Override the Auto-configuration
6.7.6. Java Configuration without Spring Boot 2.x
6.7.7. Additional Resources
6.8. OAuth 2.0 Resource Server
6.8.1. Dependencies
6.8.2. Minimal Configuration
Specifying the Authorization Server
Startup Expectations
Runtime Expectations
6.8.3. Specifying the Authorization Server JWK Set Uri Directly
6.8.4. Overriding or Replacing Boot Auto Configuration
Using jwkSetUri()
Using decoder()
Exposing a JwtDecoder @Bean
6.8.5. Configuring Authorization
Extracting Authorities Manually
6.8.6. Configuring Validation
Customizing Timestamp Validation
Configuring a Custom Validator
6.8.7. Configuring Claim Set Mapping
Customizing the Conversion of a Single Claim
Adding a Claim
Removing a Claim
Renaming a Claim
6.8.8. Configuring Timeouts
6.9. Authentication
6.9.1. In-Memory Authentication
6.9.2. JDBC Authentication
6.9.3. LDAP Authentication
6.9.4. AuthenticationProvider
6.9.5. UserDetailsService
6.10. Multiple HttpSecurity
6.11. Method Security
6.11.1. EnableGlobalMethodSecurity
6.11.2. GlobalMethodSecurityConfiguration
6.12. Post Processing Configured Objects
6.13. Custom DSLs
7. Security Namespace Configuration
7.1. Introduction
7.1.1. Design of the Namespace
7.2. Getting Started with Security Namespace Configuration
7.2.1. web.xml Configuration
7.2.2. A Minimal <http> Configuration
7.2.3. Form and Basic Login Options
Setting a Default Post-Login Destination
7.2.4. Logout Handling
7.2.5. Using other Authentication Providers
Adding a Password Encoder
7.3. Advanced Web Features
7.3.1. Remember-Me Authentication
7.3.2. Adding HTTP/HTTPS Channel Security
7.3.3. Session Management
Detecting Timeouts
Concurrent Session Control
Session Fixation Attack Protection
7.3.4. OpenID Support
Attribute Exchange
7.3.5. Response Headers
7.3.6. Adding in Your Own Filters
Setting a Custom AuthenticationEntryPoint
7.4. Method Security
7.4.1. The <global-method-security> Element
Adding Security Pointcuts using protect-pointcut
7.5. The Default AccessDecisionManager
7.5.1. Customizing the AccessDecisionManager
7.6. The Authentication Manager and the Namespace
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
GrantedAuthority
Summary
8.1.3. Authentication
What is authentication in Spring Security?
Setting the SecurityContextHolder Contents Directly
8.1.4. Authentication in a Web Application
ExceptionTranslationFilter
AuthenticationEntryPoint
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.1.6. Localization
8.2. Core Services
8.2.1. The AuthenticationManager, ProviderManager and AuthenticationProvider
Erasing Credentials on Successful Authentication
DaoAuthenticationProvider
8.2.2. UserDetailsService Implementations
In-Memory Authentication
JdbcDaoImpl
8.2.3. Password Encoding
Password History
DelegatingPasswordEncoder
BCryptPasswordEncoder
Pbkdf2PasswordEncoder
SCryptPasswordEncoder
Other PasswordEncoders
8.2.4. Jackson Support
9. Testing
9.1. Testing Method Security
9.1.1. Security Test Setup
9.1.2. @WithMockUser
9.1.3. @WithAnonymousUser
9.1.4. @WithUserDetails
9.1.5. @WithSecurityContext
9.1.6. Test Meta Annotations
9.2. Spring MVC Test Integration
9.2.1. Setting Up MockMvc and Spring Security
9.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
9.2.3. SecurityMockMvcRequestBuilders
Testing Form Based Authentication
Testing Logout
9.2.4. SecurityMockMvcResultMatchers
Unauthenticated Assertion
Authenticated Assertion
10. Web Application Security
10.1. The Security Filter Chain
10.1.1. DelegatingFilterProxy
10.1.2. FilterChainProxy
Bypassing the Filter Chain
10.1.3. Filter Ordering
10.1.4. Request Matching and HttpFirewall
10.1.5. Use with other Filter-Based Frameworks
10.1.6. Advanced Namespace Configuration
10.2. Core Security Filters
10.2.1. FilterSecurityInterceptor
10.2.2. ExceptionTranslationFilter
AuthenticationEntryPoint
AccessDeniedHandler
SavedRequest s and the RequestCache Interface
10.2.3. SecurityContextPersistenceFilter
SecurityContextRepository
10.2.4. UsernamePasswordAuthenticationFilter
Application Flow on Authentication Success and Failure
10.3. Servlet API integration
10.3.1. Servlet 2.5+ Integration
HttpServletRequest.getRemoteUser()
HttpServletRequest.getUserPrincipal()
HttpServletRequest.isUserInRole(String)
10.3.2. Servlet 3+ Integration
HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)
HttpServletRequest.login(String,String)
HttpServletRequest.logout()
AsyncContext.start(Runnable)
Async Servlet Support
10.3.3. Servlet 3.1+ Integration
HttpServletRequest#changeSessionId()
10.4. Basic and Digest Authentication
10.4.1. BasicAuthenticationFilter
Configuration
10.4.2. DigestAuthenticationFilter
Configuration
10.5. Remember-Me Authentication
10.5.1. Overview
10.5.2. Simple Hash-Based Token Approach
10.5.3. Persistent Token Approach
10.5.4. Remember-Me Interfaces and Implementations
TokenBasedRememberMeServices
PersistentTokenBasedRememberMeServices
10.6. Cross Site Request Forgery (CSRF)
10.6.1. CSRF Attacks
10.6.2. Synchronizer Token Pattern
10.6.3. When to use CSRF protection
CSRF protection and JSON
CSRF and Stateless Browser Applications
10.6.4. Using Spring Security CSRF Protection
Use proper HTTP verbs
Configure CSRF Protection
Include the CSRF Token
10.6.5. CSRF Caveats
Timeouts
Logging In
Logging Out
Multipart (file upload)
HiddenHttpMethodFilter
10.6.6. Overriding Defaults
10.7. CORS
10.8. Security HTTP Response Headers
10.8.1. Default Security Headers
Cache Control
Content Type Options
HTTP Strict Transport Security (HSTS)
HTTP Public Key Pinning (HPKP)
X-Frame-Options
X-XSS-Protection
Content Security Policy (CSP)
Referrer Policy
Feature Policy
10.8.2. Custom Headers
Static Headers
Headers Writer
DelegatingRequestMatcherHeaderWriter
10.9. Session Management
10.9.1. SessionManagementFilter
10.9.2. SessionAuthenticationStrategy
10.9.3. Concurrency Control
Querying the SessionRegistry for currently authenticated users and their sessions
10.10. Anonymous Authentication
10.10.1. Overview
10.10.2. Configuration
10.10.3. AuthenticationTrustResolver
10.11. WebSocket Security
10.11.1. WebSocket Configuration
10.11.2. WebSocket Authentication
10.11.3. WebSocket Authorization
WebSocket Authorization Notes
Outbound Messages
10.11.4. Enforcing Same Origin Policy
Why Same Origin?
Spring WebSocket Allowed Origin
Adding CSRF to Stomp Headers
Disable CSRF within WebSockets
10.11.5. Working with SockJS
SockJS & frame-options
SockJS & Relaxing CSRF
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
12. Additional Topics
12.1. Domain Object Security (ACLs)
12.1.1. Overview
12.1.2. Key Concepts
12.1.3. Getting Started
12.2. Pre-Authentication Scenarios
12.2.1. Pre-Authentication Framework Classes
AbstractPreAuthenticatedProcessingFilter
PreAuthenticatedAuthenticationProvider
Http403ForbiddenEntryPoint
12.2.2. Concrete Implementations
Request-Header Authentication (Siteminder)
Java EE Container Authentication
12.3. LDAP Authentication
12.3.1. Overview
12.3.2. Using LDAP with Spring Security
12.3.3. Configuring an LDAP Server
Using an Embedded Test Server
Using Bind Authentication
Loading Authorities
12.3.4. Implementation Classes
LdapAuthenticator Implementations
Connecting to the LDAP Server
LDAP Search Objects
LdapAuthoritiesPopulator
Spring Bean Configuration
LDAP Attributes and Customized UserDetails
12.3.5. Active Directory Authentication
ActiveDirectoryLdapAuthenticationProvider
12.4. OAuth 2.0 Login — Advanced Configuration
12.4.1. OAuth 2.0 Login Page
12.4.2. Redirection Endpoint
12.4.3. UserInfo Endpoint
Mapping User Authorities
Configuring a Custom OAuth2User
OAuth 2.0 UserService
OpenID Connect 1.0 UserService
13. WebClient for Servlet Environments
13.1. WebClient OAuth2 Setup
13.2. Implicit OAuth2AuthorizedClient
13.3. Explicit OAuth2AuthorizedClient
13.4. clientRegistrationId
13.5. JSP Tag Libraries
13.5.1. Declaring the Taglib
13.5.2. The authorize Tag
Disabling Tag Authorization for Testing
13.5.3. The authentication Tag
13.5.4. The accesscontrollist Tag
13.5.5. The csrfInput Tag
13.5.6. The csrfMetaTags Tag
13.6. Java Authentication and Authorization Service (JAAS) Provider
13.6.1. Overview
13.6.2. AbstractJaasAuthenticationProvider
JAAS CallbackHandler
JAAS AuthorityGranter
13.6.3. DefaultJaasAuthenticationProvider
InMemoryConfiguration
DefaultJaasAuthenticationProvider Example Configuration
13.6.4. JaasAuthenticationProvider
13.6.5. Running as a Subject
13.7. CAS Authentication
13.7.1. Overview
13.7.2. How CAS Works
Spring Security and CAS Interaction Sequence
13.7.3. Configuration of CAS Client
Service Ticket Authentication
Single Logout
Authenticating to a Stateless Service with CAS
Proxy Ticket Authentication
13.8. X.509 Authentication
13.8.1. Overview
13.8.2. Adding X.509 Authentication to Your Web Application
13.8.3. Setting up SSL in Tomcat
13.9. Run-As Authentication Replacement
13.9.1. Overview
13.9.2. Configuration
13.10. Spring Security Crypto Module
13.10.1. Introduction
13.10.2. Encryptors
BytesEncryptor
TextEncryptor
13.10.3. Key Generators
BytesKeyGenerator
StringKeyGenerator
13.10.4. Password Encoding
13.11. Concurrency Support
13.11.1. DelegatingSecurityContextRunnable
13.11.2. DelegatingSecurityContextExecutor
13.11.3. Spring Security Concurrency Classes
13.12. Spring MVC Integration
13.12.1. @EnableWebMvcSecurity
13.12.2. MvcRequestMatcher
13.12.3. @AuthenticationPrincipal
13.12.4. Spring MVC Async Integration
13.12.5. Spring MVC and CSRF Integration
Automatic Token Inclusion
Resolving the CsrfToken
14. Spring Data Integration
14.1. Spring Data & Spring Security Configuration
14.2. Security Expressions within @Query
15. Appendix
15.1. Security Database Schema
15.1.1. User Schema
For Oracle database
Group Authorities
15.1.2. Persistent Login (Remember-Me) Schema
15.1.3. ACL Schema
HyperSQL
PostgreSQL
MySQL and MariaDB
Microsoft SQL Server
Oracle Database
15.2. The Security Namespace
15.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>
15.2.2. WebSocket Security
<websocket-message-broker>
<intercept-message>
15.2.3. Authentication Services
<authentication-manager>
<authentication-provider>
<jdbc-user-service>
<password-encoder>
<user-service>
<user>
15.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>
15.2.5. LDAP Namespace Options
Defining the LDAP Server using the
<ldap-authentication-provider>
<password-compare>
<ldap-user-service>
15.3. Spring Security Dependencies
15.3.1. spring-security-core
15.3.2. spring-security-remoting
15.3.3. spring-security-web
15.3.4. spring-security-ldap
15.3.5. spring-security-config
15.3.6. spring-security-acl
15.3.7. spring-security-cas
15.3.8. spring-security-openid
15.3.9. spring-security-taglibs
15.4. Proxy Server Configuration
15.5. Spring Security FAQ
15.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.
15.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.
15.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?
15.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
16. WebFlux Security
16.1. Minimal WebFlux Security Configuration
16.2. Explicit WebFlux Security Configuration
17. Default Security Headers
17.1. Cache Control
17.2. Content Type Options
17.3. HTTP Strict Transport Security (HSTS)
17.4. X-Frame-Options
17.5. X-XSS-Protection
17.6. Content Security Policy (CSP)
17.6.1. Configuring Content Security Policy
17.6.2. Additional Resources
17.7. Referrer Policy
17.7.1. Configuring Referrer Policy
17.8. Feature Policy
17.8.1. Configuring Feature Policy
18. Redirect to HTTPS
19. OAuth2 WebFlux
19.1. OAuth 2.0 Login
19.1.1. Spring Boot 2.0 Sample
Initial setup
Setting the redirect URI
Configure application.yml
Boot up the application
19.1.2. Using OpenID Provider Configuration
19.1.3. Explicit OAuth2 Login Configuration
19.2. OAuth2 Client
19.3. OAuth2 Resource Server
19.3.1. Dependencies
19.3.2. Minimal Configuration
Specify the Authorization Server
Startup Expectations
Runtime Expectations
Specifying the Authorization Server JWK Set Uri Directly
Overriding or Replacing Boot Auto Configuration
Configuring Authorization
Configuring Validation
20. @RegisteredOAuth2AuthorizedClient
21. WebClient
21.1. WebClient OAuth2 Setup
21.2. Implicit OAuth2AuthorizedClient
21.3. Explicit OAuth2AuthorizedClient
21.4. clientRegistrationId
22. EnableReactiveMethodSecurity
23. Reactive Test Support
23.1. Testing Reactive Method Security
23.2. WebTestClientSupport
23.2.1. Authentication
23.2.2. CSRF Support