0
# HTTP Security Configurers
1
2
Spring Security Config provides specialized configurers for different aspects of HTTP security. These configurers work with HttpSecurity to provide fluent configuration APIs for authentication, authorization, and security protection features.
3
4
## Authentication Configurers
5
6
### FormLoginConfigurer
7
8
Configuration for form-based authentication with login pages and handlers.
9
10
```java { .api }
11
public final class FormLoginConfigurer<H extends HttpSecurityBuilder<H>>
12
extends AbstractAuthenticationFilterConfigurer<H, FormLoginConfigurer<H>, UsernamePasswordAuthenticationFilter> {
13
14
// Login Page Configuration
15
public FormLoginConfigurer<H> loginPage(String loginPage);
16
public FormLoginConfigurer<H> loginProcessingUrl(String loginProcessingUrl);
17
18
// Success Handling
19
public FormLoginConfigurer<H> defaultSuccessUrl(String defaultSuccessUrl);
20
public FormLoginConfigurer<H> defaultSuccessUrl(String defaultSuccessUrl, boolean alwaysUse);
21
public FormLoginConfigurer<H> successForwardUrl(String forwardUrl);
22
public FormLoginConfigurer<H> successHandler(AuthenticationSuccessHandler successHandler);
23
24
// Failure Handling
25
public FormLoginConfigurer<H> failureUrl(String authenticationFailureUrl);
26
public FormLoginConfigurer<H> failureForwardUrl(String forwardUrl);
27
public FormLoginConfigurer<H> failureHandler(AuthenticationFailureHandler authenticationFailureHandler);
28
29
// Parameter Names
30
public FormLoginConfigurer<H> usernameParameter(String usernameParameter);
31
public FormLoginConfigurer<H> passwordParameter(String passwordParameter);
32
33
// Permission Configuration
34
public FormLoginConfigurer<H> permitAll();
35
public FormLoginConfigurer<H> permitAll(boolean permitAll);
36
}
37
```
38
39
**Usage Example:**
40
41
```java
42
http.formLogin(form -> form
43
.loginPage("/custom-login")
44
.loginProcessingUrl("/authenticate")
45
.usernameParameter("email")
46
.passwordParameter("password")
47
.defaultSuccessUrl("/dashboard", true)
48
.failureUrl("/login?error=true")
49
.successHandler((request, response, authentication) -> {
50
response.sendRedirect("/welcome");
51
})
52
.failureHandler((request, response, exception) -> {
53
request.setAttribute("error", exception.getMessage());
54
request.getRequestDispatcher("/login?error").forward(request, response);
55
})
56
.permitAll()
57
);
58
```
59
60
### HttpBasicConfigurer
61
62
Configuration for HTTP Basic authentication.
63
64
```java { .api }
65
public final class HttpBasicConfigurer<H extends HttpSecurityBuilder<H>>
66
extends AbstractHttpConfigurer<HttpBasicConfigurer<H>, H> {
67
68
// Realm Configuration
69
public HttpBasicConfigurer<H> realmName(String realmName);
70
71
// Authentication Entry Point
72
public HttpBasicConfigurer<H> authenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint);
73
74
// Security Context Configuration
75
public HttpBasicConfigurer<H> securityContextRepository(SecurityContextRepository securityContextRepository);
76
}
77
```
78
79
**Usage Example:**
80
81
```java
82
http.httpBasic(basic -> basic
83
.realmName("My Application")
84
.authenticationEntryPoint(customBasicAuthenticationEntryPoint())
85
);
86
```
87
88
### OAuth2LoginConfigurer
89
90
Configuration for OAuth2/OpenID Connect authentication.
91
92
```java { .api }
93
public final class OAuth2LoginConfigurer<H extends HttpSecurityBuilder<H>>
94
extends AbstractAuthenticationFilterConfigurer<H, OAuth2LoginConfigurer<H>, OAuth2LoginAuthenticationFilter> {
95
96
// Client Registration
97
public OAuth2LoginConfigurer<H> clientRegistrationRepository(ClientRegistrationRepository clientRegistrationRepository);
98
public OAuth2LoginConfigurer<H> authorizedClientRepository(OAuth2AuthorizedClientRepository authorizedClientRepository);
99
public OAuth2LoginConfigurer<H> authorizedClientService(OAuth2AuthorizedClientService authorizedClientService);
100
101
// Login Page Configuration
102
public OAuth2LoginConfigurer<H> loginPage(String loginPage);
103
public OAuth2LoginConfigurer<H> loginProcessingUrl(String loginProcessingUrl);
104
105
// Endpoint Configuration
106
public OAuth2LoginConfigurer<H> authorizationEndpoint(Customizer<AuthorizationEndpointConfig> authorizationEndpointCustomizer);
107
public OAuth2LoginConfigurer<H> redirectionEndpoint(Customizer<RedirectionEndpointConfig> redirectionEndpointCustomizer);
108
public OAuth2LoginConfigurer<H> tokenEndpoint(Customizer<TokenEndpointConfig> tokenEndpointCustomizer);
109
public OAuth2LoginConfigurer<H> userInfoEndpoint(Customizer<UserInfoEndpointConfig> userInfoEndpointCustomizer);
110
111
// OIDC Configuration
112
public OAuth2LoginConfigurer<H> oidcLogout(Customizer<OidcLogoutConfigurer<H>> oidcLogoutCustomizer);
113
}
114
```
115
116
**Usage Example:**
117
118
```java
119
http.oauth2Login(oauth2 -> oauth2
120
.loginPage("/oauth2/authorization/google")
121
.authorizationEndpoint(authorization -> authorization
122
.baseUri("/oauth2/authorize")
123
.authorizationRequestRepository(cookieRequestRepository())
124
)
125
.tokenEndpoint(token -> token
126
.accessTokenResponseClient(accessTokenResponseClient())
127
)
128
.userInfoEndpoint(userInfo -> userInfo
129
.userService(oauth2UserService())
130
.oidcUserService(oidcUserService())
131
)
132
.successHandler(oauth2AuthenticationSuccessHandler())
133
.failureHandler(oauth2AuthenticationFailureHandler())
134
);
135
```
136
137
### X509Configurer
138
139
Configuration for X.509 certificate authentication.
140
141
```java { .api }
142
public final class X509Configurer<H extends HttpSecurityBuilder<H>>
143
extends AbstractHttpConfigurer<X509Configurer<H>, H> {
144
145
// Principal Extraction
146
public X509Configurer<H> subjectPrincipalRegex(String subjectPrincipalRegex);
147
public X509Configurer<H> x509PrincipalExtractor(X509PrincipalExtractor principalExtractor);
148
149
// User Details Service
150
public X509Configurer<H> userDetailsService(UserDetailsService userDetailsService);
151
152
// Authentication Details Source
153
public X509Configurer<H> authenticationDetailsSource(AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource);
154
}
155
```
156
157
**Usage Example:**
158
159
```java
160
http.x509(x509 -> x509
161
.subjectPrincipalRegex("CN=(.*?)(?:,|$)")
162
.userDetailsService(x509UserDetailsService())
163
);
164
```
165
166
## Authorization Configurers
167
168
### AuthorizeHttpRequestsConfigurer
169
170
Modern HTTP request authorization configuration using AuthorizationManager.
171
172
```java { .api }
173
public final class AuthorizeHttpRequestsConfigurer<H extends HttpSecurityBuilder<H>>
174
extends AbstractRequestMatcherRegistry<AuthorizeHttpRequestsConfigurer<H>.AuthorizationManagerRequestMatcherRegistry> {
175
176
public class AuthorizationManagerRequestMatcherRegistry extends AbstractRequestMatcherRegistry<AuthorizationManagerRequestMatcherRegistry> {
177
178
// Request Matching
179
public AuthorizationManagerRequestMatcherRegistry requestMatchers(String... patterns);
180
public AuthorizationManagerRequestMatcherRegistry requestMatchers(HttpMethod method, String... patterns);
181
public AuthorizationManagerRequestMatcherRegistry requestMatchers(RequestMatcher... requestMatchers);
182
public AuthorizationManagerRequestMatcherRegistry anyRequest();
183
184
// Authorization Rules
185
public AuthorizationManagerRequestMatcherRegistry permitAll();
186
public AuthorizationManagerRequestMatcherRegistry denyAll();
187
public AuthorizationManagerRequestMatcherRegistry authenticated();
188
public AuthorizationManagerRequestMatcherRegistry anonymous();
189
public AuthorizationManagerRequestMatcherRegistry rememberMe();
190
public AuthorizationManagerRequestMatcherRegistry fullyAuthenticated();
191
192
// Role-based Authorization
193
public AuthorizationManagerRequestMatcherRegistry hasRole(String role);
194
public AuthorizationManagerRequestMatcherRegistry hasAnyRole(String... roles);
195
public AuthorizationManagerRequestMatcherRegistry hasAuthority(String authority);
196
public AuthorizationManagerRequestMatcherRegistry hasAnyAuthority(String... authorities);
197
198
// IP-based Authorization
199
public AuthorizationManagerRequestMatcherRegistry hasIpAddress(String ipAddress);
200
201
// Custom Authorization
202
public AuthorizationManagerRequestMatcherRegistry access(AuthorizationManager<RequestAuthorizationContext> manager);
203
public AuthorizationManagerRequestMatcherRegistry access(String attribute);
204
}
205
}
206
```
207
208
**Usage Example:**
209
210
```java
211
http.authorizeHttpRequests(authz -> authz
212
.requestMatchers("/", "/home", "/public/**").permitAll()
213
.requestMatchers("/admin/**").hasRole("ADMIN")
214
.requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
215
.requestMatchers(HttpMethod.POST, "/api/**").hasAuthority("WRITE")
216
.requestMatchers("/internal/**").hasIpAddress("192.168.1.0/24")
217
.anyRequest().authenticated()
218
);
219
```
220
221
### ExpressionUrlAuthorizationConfigurer
222
223
Legacy expression-based URL authorization configuration.
224
225
```java { .api }
226
public final class ExpressionUrlAuthorizationConfigurer<H extends HttpSecurityBuilder<H>>
227
extends AbstractInterceptUrlConfigurer<ExpressionUrlAuthorizationConfigurer<H>, H> {
228
229
public class ExpressionInterceptUrlRegistry extends AbstractRequestMatcherMappingConfigurer<List<AccessConfigAttribute>, ExpressionInterceptUrlRegistry> {
230
231
// Request Matching
232
public ExpressionInterceptUrlRegistry requestMatchers(String... patterns);
233
public ExpressionInterceptUrlRegistry requestMatchers(HttpMethod method, String... patterns);
234
public ExpressionInterceptUrlRegistry anyRequest();
235
236
// Authorization Rules
237
public ExpressionInterceptUrlRegistry permitAll();
238
public ExpressionInterceptUrlRegistry denyAll();
239
public ExpressionInterceptUrlRegistry authenticated();
240
public ExpressionInterceptUrlRegistry fullyAuthenticated();
241
public ExpressionInterceptUrlRegistry anonymous();
242
public ExpressionInterceptUrlRegistry rememberMe();
243
244
// Role-based Authorization
245
public ExpressionInterceptUrlRegistry hasRole(String role);
246
public ExpressionInterceptUrlRegistry hasAnyRole(String... roles);
247
public ExpressionInterceptUrlRegistry hasAuthority(String authority);
248
public ExpressionInterceptUrlRegistry hasAnyAuthority(String... authorities);
249
250
// IP-based Authorization
251
public ExpressionInterceptUrlRegistry hasIpAddress(String ipAddress);
252
253
// Expression-based Authorization
254
public ExpressionInterceptUrlRegistry access(String attribute);
255
}
256
}
257
```
258
259
## Security Protection Configurers
260
261
### CsrfConfigurer
262
263
Configuration for Cross-Site Request Forgery protection.
264
265
```java { .api }
266
public final class CsrfConfigurer<H extends HttpSecurityBuilder<H>>
267
extends AbstractHttpConfigurer<CsrfConfigurer<H>, H> {
268
269
// Token Repository
270
public CsrfConfigurer<H> csrfTokenRepository(CsrfTokenRepository csrfTokenRepository);
271
272
// Request Matching
273
public CsrfConfigurer<H> requireCsrfProtectionMatcher(RequestMatcher requireCsrfProtectionMatcher);
274
public CsrfConfigurer<H> ignoringRequestMatchers(RequestMatcher... requestMatchers);
275
public CsrfConfigurer<H> ignoringRequestMatchers(String... patterns);
276
277
// Session Authentication Strategy
278
public CsrfConfigurer<H> sessionAuthenticationStrategy(SessionAuthenticationStrategy sessionAuthenticationStrategy);
279
280
// Token Handler
281
public CsrfConfigurer<H> csrfTokenRequestHandler(CsrfTokenRequestHandler requestHandler);
282
}
283
```
284
285
**Usage Example:**
286
287
```java
288
http.csrf(csrf -> csrf
289
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
290
.ignoringRequestMatchers("/api/webhook/**")
291
.sessionAuthenticationStrategy(new ChangeSessionIdAuthenticationStrategy())
292
);
293
```
294
295
### CorsConfigurer
296
297
Configuration for Cross-Origin Resource Sharing.
298
299
```java { .api }
300
public class CorsConfigurer<H extends HttpSecurityBuilder<H>>
301
extends AbstractHttpConfigurer<CorsConfigurer<H>, H> {
302
303
// Configuration Source
304
public CorsConfigurer<H> configurationSource(CorsConfigurationSource configurationSource);
305
306
// Built-in Configuration
307
public CorsConfigurer<H> and();
308
}
309
```
310
311
**Usage Example:**
312
313
```java
314
http.cors(cors -> cors
315
.configurationSource(request -> {
316
CorsConfiguration config = new CorsConfiguration();
317
config.setAllowedOrigins(Arrays.asList("https://example.com"));
318
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
319
config.setAllowedHeaders(Arrays.asList("*"));
320
config.setAllowCredentials(true);
321
return config;
322
})
323
);
324
```
325
326
### HeadersConfigurer
327
328
Configuration for security-related HTTP headers.
329
330
```java { .api }
331
public final class HeadersConfigurer<H extends HttpSecurityBuilder<H>>
332
extends AbstractHttpConfigurer<HeadersConfigurer<H>, H> {
333
334
// Content Type Options
335
public HeadersConfigurer<H> contentTypeOptions(Customizer<ContentTypeOptionsConfig> contentTypeOptionsCustomizer);
336
337
// Frame Options
338
public HeadersConfigurer<H> frameOptions(Customizer<FrameOptionsConfig> frameOptionsCustomizer);
339
340
// HTTP Strict Transport Security
341
public HeadersConfigurer<H> httpStrictTransportSecurity(Customizer<HstsConfig> hstsCustomizer);
342
343
// Content Security Policy
344
public HeadersConfigurer<H> contentSecurityPolicy(String policyDirectives);
345
public HeadersConfigurer<H> contentSecurityPolicy(Customizer<ContentSecurityPolicyConfig> contentSecurityPolicyCustomizer);
346
347
// Referrer Policy
348
public HeadersConfigurer<H> referrerPolicy(ReferrerPolicy policy);
349
public HeadersConfigurer<H> referrerPolicy(Customizer<ReferrerPolicyConfig> referrerPolicyCustomizer);
350
351
// Cross-Origin Policies
352
public HeadersConfigurer<H> crossOriginEmbedderPolicy(CrossOriginEmbedderPolicy policy);
353
public HeadersConfigurer<H> crossOriginOpenerPolicy(CrossOriginOpenerPolicy policy);
354
public HeadersConfigurer<H> crossOriginResourcePolicy(CrossOriginResourcePolicy policy);
355
356
// Cache Control
357
public HeadersConfigurer<H> cacheControl(Customizer<CacheControlConfig> cacheControlCustomizer);
358
359
// Default Headers
360
public HeadersConfigurer<H> defaultsDisabled();
361
}
362
```
363
364
**Usage Example:**
365
366
```java
367
http.headers(headers -> headers
368
.frameOptions(frameOptions -> frameOptions.sameOrigin())
369
.contentSecurityPolicy("default-src 'self'; script-src 'self' 'unsafe-inline'")
370
.httpStrictTransportSecurity(hsts -> hsts
371
.maxAgeInSeconds(31536000)
372
.includeSubdomains(true)
373
.preload(true)
374
)
375
.referrerPolicy(ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
376
);
377
```
378
379
## Session Management Configurers
380
381
### SessionManagementConfigurer
382
383
Configuration for HTTP session management and security.
384
385
```java { .api }
386
public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
387
extends AbstractHttpConfigurer<SessionManagementConfigurer<H>, H> {
388
389
// Session Creation Policy
390
public SessionManagementConfigurer<H> sessionCreationPolicy(SessionCreationPolicy sessionCreationPolicy);
391
392
// Session Authentication Strategy
393
public SessionManagementConfigurer<H> sessionAuthenticationStrategy(SessionAuthenticationStrategy sessionAuthenticationStrategy);
394
395
// Session Fixation Protection
396
public SessionManagementConfigurer<H> sessionFixation(Customizer<SessionFixationConfigurer> sessionFixationCustomizer);
397
398
// Concurrent Sessions
399
public SessionManagementConfigurer<H> maximumSessions(int maximumSessions);
400
public SessionManagementConfigurer<H> maxSessionsPreventsLogin(boolean maxSessionsPreventsLogin);
401
public SessionManagementConfigurer<H> sessionRegistry(SessionRegistry sessionRegistry);
402
public SessionManagementConfigurer<H> expiredUrl(String expiredUrl);
403
public SessionManagementConfigurer<H> expiredSessionStrategy(SessionInformationExpiredStrategy expiredSessionStrategy);
404
405
// Invalid Session Handling
406
public SessionManagementConfigurer<H> invalidSessionUrl(String invalidSessionUrl);
407
public SessionManagementConfigurer<H> invalidSessionStrategy(InvalidSessionStrategy invalidSessionStrategy);
408
}
409
```
410
411
**Usage Example:**
412
413
```java
414
http.sessionManagement(session -> session
415
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
416
.maximumSessions(1)
417
.maxSessionsPreventsLogin(false)
418
.expiredUrl("/session-expired")
419
.sessionRegistry(sessionRegistry())
420
.and()
421
.sessionFixation(sessionFixation -> sessionFixation.migrateSession())
422
.invalidSessionUrl("/login")
423
);
424
```
425
426
### LogoutConfigurer
427
428
Configuration for logout functionality and handlers.
429
430
```java { .api }
431
public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>>
432
extends AbstractHttpConfigurer<LogoutConfigurer<H>, H> {
433
434
// Logout URL Configuration
435
public LogoutConfigurer<H> logoutUrl(String logoutUrl);
436
public LogoutConfigurer<H> logoutRequestMatcher(RequestMatcher logoutRequestMatcher);
437
438
// Success Handling
439
public LogoutConfigurer<H> logoutSuccessUrl(String logoutSuccessUrl);
440
public LogoutConfigurer<H> logoutSuccessHandler(LogoutSuccessHandler logoutSuccessHandler);
441
442
// Session Invalidation
443
public LogoutConfigurer<H> invalidateHttpSession(boolean invalidateHttpSession);
444
445
// Cookie Deletion
446
public LogoutConfigurer<H> deleteCookies(String... cookieNamesToClear);
447
448
// Logout Handlers
449
public LogoutConfigurer<H> addLogoutHandler(LogoutHandler logoutHandler);
450
451
// Security Context
452
public LogoutConfigurer<H> clearAuthentication(boolean clearAuthentication);
453
454
// Permission Configuration
455
public LogoutConfigurer<H> permitAll();
456
public LogoutConfigurer<H> permitAll(boolean permitAll);
457
}
458
```
459
460
**Usage Example:**
461
462
```java
463
http.logout(logout -> logout
464
.logoutUrl("/logout")
465
.logoutSuccessUrl("/login?logout")
466
.invalidateHttpSession(true)
467
.deleteCookies("JSESSIONID", "remember-me")
468
.addLogoutHandler(customLogoutHandler())
469
.logoutSuccessHandler((request, response, authentication) -> {
470
response.sendRedirect("/goodbye");
471
})
472
.clearAuthentication(true)
473
.permitAll()
474
);
475
```
476
477
## Advanced Configurers
478
479
### ExceptionHandlingConfigurer
480
481
Configuration for security exception handling.
482
483
```java { .api }
484
public final class ExceptionHandlingConfigurer<H extends HttpSecurityBuilder<H>>
485
extends AbstractHttpConfigurer<ExceptionHandlingConfigurer<H>, H> {
486
487
// Authentication Entry Point
488
public ExceptionHandlingConfigurer<H> authenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint);
489
490
// Access Denied Handling
491
public ExceptionHandlingConfigurer<H> accessDeniedHandler(AccessDeniedHandler accessDeniedHandler);
492
public ExceptionHandlingConfigurer<H> accessDeniedPage(String accessDeniedUrl);
493
494
// Default Entry Point Configuration
495
public ExceptionHandlingConfigurer<H> defaultAuthenticationEntryPointFor(AuthenticationEntryPoint entryPoint, RequestMatcher preferredMatcher);
496
}
497
```
498
499
**Usage Example:**
500
501
```java
502
http.exceptionHandling(exceptions -> exceptions
503
.authenticationEntryPoint((request, response, authException) -> {
504
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
505
})
506
.accessDeniedHandler((request, response, accessDeniedException) -> {
507
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
508
})
509
.accessDeniedPage("/access-denied")
510
);
511
```
512
513
### RequestCacheConfigurer
514
515
Configuration for request caching during authentication flows.
516
517
```java { .api }
518
public final class RequestCacheConfigurer<H extends HttpSecurityBuilder<H>>
519
extends AbstractHttpConfigurer<RequestCacheConfigurer<H>, H> {
520
521
// Request Cache Implementation
522
public RequestCacheConfigurer<H> requestCache(RequestCache requestCache);
523
524
// Request Matchers
525
public RequestCacheConfigurer<H> requestMatchers(RequestMatcher... requestMatchers);
526
}
527
```
528
529
**Usage Example:**
530
531
```java
532
http.requestCache(cache -> cache
533
.requestCache(new HttpSessionRequestCache())
534
.requestMatchers(new AntPathRequestMatcher("/secure/**"))
535
);
536
```