0
# Spring Security Web
1
2
Spring Security Web module provides comprehensive web security features for Spring-based applications, including servlet-based authentication, authorization, CSRF protection, session management, and security filter chain implementation. It serves as the core web security infrastructure for both traditional servlet-based and reactive Spring applications.
3
4
## Package Information
5
6
- **Package Name**: org.springframework.security:spring-security-web
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**:
10
11
Maven:
12
```xml
13
<dependency>
14
<groupId>org.springframework.security</groupId>
15
<artifactId>spring-security-web</artifactId>
16
<version>6.5.1</version>
17
</dependency>
18
```
19
20
Gradle:
21
```groovy
22
implementation 'org.springframework.security:spring-security-web:6.5.1'
23
```
24
25
## Core Imports
26
27
```java
28
import org.springframework.security.web.SecurityFilterChain;
29
import org.springframework.security.web.FilterChainProxy;
30
import org.springframework.security.web.AuthenticationEntryPoint;
31
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
32
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
33
import org.springframework.security.web.access.AccessDeniedHandler;
34
import org.springframework.security.web.csrf.CsrfFilter;
35
import org.springframework.security.web.context.SecurityContextRepository;
36
```
37
38
## Basic Usage
39
40
```java
41
import org.springframework.security.web.SecurityFilterChain;
42
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
43
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
44
import org.springframework.security.web.csrf.CsrfFilter;
45
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
46
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
47
48
// Basic filter chain configuration
49
public class SecurityConfig {
50
51
@Bean
52
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
53
return http
54
.authorizeHttpRequests(auth -> auth
55
.requestMatchers("/login", "/public/**").permitAll()
56
.anyRequest().authenticated()
57
)
58
.formLogin(form -> form
59
.loginPage("/login")
60
.defaultSuccessUrl("/dashboard")
61
)
62
.csrf(csrf -> csrf
63
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
64
)
65
.build();
66
}
67
}
68
69
// Manual filter chain setup
70
List<Filter> filters = Arrays.asList(
71
new SecurityContextHolderFilter(new HttpSessionSecurityContextRepository()),
72
new CsrfFilter(new HttpSessionCsrfTokenRepository()),
73
new UsernamePasswordAuthenticationFilter()
74
);
75
76
SecurityFilterChain chain = new DefaultSecurityFilterChain(
77
new AntPathRequestMatcher("/**"),
78
filters
79
);
80
81
FilterChainProxy proxy = new FilterChainProxy(chain);
82
```
83
84
## Architecture
85
86
Spring Security Web is built around a filter chain architecture that processes HTTP requests through a series of security filters. Key architectural components:
87
88
- **Filter Chain Proxy**: Central dispatcher that manages multiple security filter chains
89
- **Security Filter Chains**: Collections of filters that handle specific security concerns
90
- **Authentication Framework**: Pluggable authentication mechanisms and handlers
91
- **Authorization Framework**: Access control and privilege evaluation
92
- **Security Context Management**: Thread-safe security context storage and retrieval
93
- **CSRF Protection**: Cross-site request forgery prevention
94
- **Session Management**: HTTP session security controls
95
- **Reactive Support**: WebFlux integration for reactive applications
96
97
## Capabilities
98
99
### Core Filter Chain Infrastructure
100
101
The foundation of Spring Security's web security, providing filter chain management and request processing orchestration.
102
103
```java { .api }
104
public interface SecurityFilterChain {
105
boolean matches(HttpServletRequest request);
106
List<Filter> getFilters();
107
}
108
109
public class FilterChainProxy extends GenericFilterBean {
110
public FilterChainProxy(List<SecurityFilterChain> filterChains);
111
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain);
112
public List<SecurityFilterChain> getFilterChains();
113
public void setFirewall(HttpFirewall firewall);
114
}
115
116
public class DefaultSecurityFilterChain implements SecurityFilterChain {
117
public DefaultSecurityFilterChain(RequestMatcher requestMatcher, Filter... filters);
118
public DefaultSecurityFilterChain(RequestMatcher requestMatcher, List<Filter> filters);
119
}
120
```
121
122
[Filter Chain and Security Infrastructure](./filter-chain.md)
123
124
### Authentication Framework
125
126
Comprehensive authentication mechanisms including form-based, HTTP Basic, and pluggable authentication converters.
127
128
```java { .api }
129
public interface AuthenticationSuccessHandler {
130
void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
131
Authentication authentication) throws IOException, ServletException;
132
}
133
134
public interface AuthenticationFailureHandler {
135
void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
136
AuthenticationException exception) throws IOException, ServletException;
137
}
138
139
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
140
public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
141
public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
142
143
public void setUsernameParameter(String usernameParameter);
144
public void setPasswordParameter(String passwordParameter);
145
}
146
```
147
148
[Authentication Framework](./authentication.md)
149
150
### Access Control and Authorization
151
152
Access control mechanisms, exception handling, and privilege evaluation for web resources.
153
154
```java { .api }
155
public interface AccessDeniedHandler {
156
void handle(HttpServletRequest request, HttpServletResponse response,
157
AccessDeniedException accessDeniedException) throws IOException, ServletException;
158
}
159
160
public class ExceptionTranslationFilter extends GenericFilterBean {
161
public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint);
162
public void setAccessDeniedHandler(AccessDeniedHandler accessDeniedHandler);
163
public void setRequestCache(RequestCache requestCache);
164
}
165
166
public interface WebInvocationPrivilegeEvaluator {
167
boolean isAllowed(String uri, Authentication authentication);
168
boolean isAllowed(HttpServletRequest request, Authentication authentication);
169
}
170
```
171
172
[Access Control and Authorization](./access-control.md)
173
174
### CSRF Protection
175
176
Cross-Site Request Forgery protection with token-based validation and multiple storage strategies.
177
178
```java { .api }
179
public interface CsrfToken {
180
String getToken();
181
String getParameterName();
182
String getHeaderName();
183
}
184
185
public interface CsrfTokenRepository {
186
CsrfToken generateToken(HttpServletRequest request);
187
void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response);
188
CsrfToken loadToken(HttpServletRequest request);
189
}
190
191
public class CsrfFilter extends OncePerRequestFilter {
192
public void setCsrfTokenRepository(CsrfTokenRepository csrfTokenRepository);
193
public void setRequireCsrfProtectionMatcher(RequestMatcher requireCsrfProtectionMatcher);
194
}
195
```
196
197
[CSRF Protection](./csrf.md)
198
199
### Security Context Management
200
201
Thread-safe security context storage, persistence, and lifecycle management across HTTP requests.
202
203
```java { .api }
204
public interface SecurityContextRepository {
205
SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder);
206
void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response);
207
boolean containsContext(HttpServletRequest request);
208
}
209
210
public class SecurityContextHolderFilter extends GenericFilterBean {
211
public SecurityContextHolderFilter(SecurityContextRepository securityContextRepository);
212
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy);
213
}
214
215
public class HttpSessionSecurityContextRepository implements SecurityContextRepository {
216
public void setAllowSessionCreation(boolean allowSessionCreation);
217
public void setDisableUrlRewriting(boolean disableUrlRewriting);
218
public void setSpringSecurityContextKey(String springSecurityContextKey);
219
}
220
```
221
222
[Security Context Management](./security-context.md)
223
224
### Session Management
225
226
HTTP session security controls including concurrent session management, session fixation protection, and invalid session handling.
227
228
```java { .api }
229
public class SessionManagementFilter extends GenericFilterBean {
230
public void setInvalidSessionStrategy(InvalidSessionStrategy invalidSessionStrategy);
231
public void setSessionInformationExpiredStrategy(SessionInformationExpiredStrategy sessionInformationExpiredStrategy);
232
}
233
234
public interface InvalidSessionStrategy {
235
void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response)
236
throws IOException, ServletException;
237
}
238
239
public interface SessionInformationExpiredStrategy {
240
void onExpiredSessionDetected(SessionInformationExpiredEvent event)
241
throws IOException, ServletException;
242
}
243
```
244
245
[Session Management](./session-management.md)
246
247
### Request Validation and Firewall
248
249
HTTP request validation, sanitization, and attack prevention through configurable firewall rules.
250
251
```java { .api }
252
public interface HttpFirewall {
253
FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException;
254
HttpServletResponse getFirewalledResponse(HttpServletResponse response);
255
}
256
257
public class StrictHttpFirewall implements HttpFirewall {
258
public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash);
259
public void setAllowUrlEncodedPercent(boolean allowUrlEncodedPercent);
260
public void setAllowSemicolon(boolean allowSemicolon);
261
public void setUnsafeAllowAnyHttpMethod(boolean unsafeAllowAnyHttpMethod);
262
}
263
264
public interface RequestRejectedHandler {
265
void handle(HttpServletRequest request, HttpServletResponse response,
266
RequestRejectedException requestRejectedException) throws IOException, ServletException;
267
}
268
```
269
270
[Request Validation and Firewall](./firewall.md)
271
272
### Request Matching and Utilities
273
274
Flexible request matching capabilities and utility classes for URL manipulation, text escaping, and security operations.
275
276
```java { .api }
277
public interface RequestMatcher {
278
boolean matches(HttpServletRequest request);
279
default MatchResult matcher(HttpServletRequest request);
280
}
281
282
public class AntPathRequestMatcher implements RequestMatcher {
283
public AntPathRequestMatcher(String pattern);
284
public AntPathRequestMatcher(String pattern, String httpMethod);
285
public AntPathRequestMatcher(String pattern, String httpMethod, boolean caseSensitive);
286
}
287
288
public final class UrlUtils {
289
public static String buildRequestUrl(HttpServletRequest request);
290
public static String buildFullRequestUrl(HttpServletRequest request);
291
public static boolean isAbsoluteUrl(String url);
292
}
293
```
294
295
[Request Matching and Utilities](./utilities.md)
296
297
### Reactive Web Security
298
299
Reactive programming support for WebFlux applications with non-blocking security filters and handlers.
300
301
```java { .api }
302
public interface SecurityWebFilterChain {
303
boolean matches(ServerWebExchange exchange);
304
Flux<WebFilter> getWebFilters();
305
}
306
307
public class WebFilterChainProxy implements WebFilter {
308
public WebFilterChainProxy(List<SecurityWebFilterChain> filters);
309
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain);
310
public void setFirewall(ServerHttpFirewall firewall);
311
}
312
313
public interface ServerAuthenticationEntryPoint {
314
Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex);
315
}
316
```
317
318
[Reactive Web Security](./reactive.md)
319
320
## Types
321
322
```java { .api }
323
// Core filter chain types
324
public interface Filter {
325
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
326
throws IOException, ServletException;
327
}
328
329
public interface FilterChain {
330
void doFilter(ServletRequest request, ServletResponse response)
331
throws IOException, ServletException;
332
}
333
334
// Security context types
335
@FunctionalInterface
336
public interface SecurityContextHolderStrategy {
337
SecurityContext getContext();
338
void setContext(SecurityContext context);
339
SecurityContext createEmptyContext();
340
void clearContext();
341
}
342
343
// Authentication types
344
public interface Authentication extends Principal, Serializable {
345
Collection<? extends GrantedAuthority> getAuthorities();
346
Object getCredentials();
347
Object getDetails();
348
Object getPrincipal();
349
boolean isAuthenticated();
350
void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;
351
}
352
353
public class AuthenticationException extends RuntimeException {
354
public AuthenticationException(String msg);
355
public AuthenticationException(String msg, Throwable cause);
356
}
357
358
// Request/Response holders
359
public class HttpRequestResponseHolder {
360
public HttpRequestResponseHolder(HttpServletRequest request, HttpServletResponse response);
361
public HttpServletRequest getRequest();
362
public HttpServletResponse getResponse();
363
}
364
365
// Reactive types (for WebFlux support)
366
public interface ServerWebExchange {
367
ServerHttpRequest getRequest();
368
ServerHttpResponse getResponse();
369
Map<String, Object> getAttributes();
370
Mono<WebSession> getSession();
371
}
372
373
// Authentication Manager types
374
public interface AuthenticationManager {
375
Authentication authenticate(Authentication authentication) throws AuthenticationException;
376
}
377
378
public interface AuthenticationManagerResolver<T> {
379
AuthenticationManager resolve(T context);
380
}
381
382
// Grant Authority types
383
public interface GrantedAuthority extends Serializable {
384
String getAuthority();
385
}
386
387
public class SimpleGrantedAuthority implements GrantedAuthority {
388
public SimpleGrantedAuthority(String role);
389
public String getAuthority();
390
}
391
392
// Request Cache types
393
public interface RequestCache {
394
void saveRequest(HttpServletRequest request, HttpServletResponse response);
395
SavedRequest getRequest(HttpServletRequest request, HttpServletResponse response);
396
HttpServletRequest getMatchingRequest(HttpServletRequest request, HttpServletResponse response);
397
void removeRequest(HttpServletRequest request, HttpServletResponse response);
398
}
399
400
public interface SavedRequest extends Serializable {
401
String getRedirectUrl();
402
List<Cookie> getCookies();
403
String getMethod();
404
List<String> getHeaderValues(String name);
405
Collection<String> getHeaderNames();
406
List<Locale> getLocales();
407
String[] getParameterValues(String name);
408
Map<String, String[]> getParameterMap();
409
}
410
```