0
# Security Builder Classes
1
2
Spring Security Config provides fluent API builders that enable declarative configuration of security components. These builders use the builder pattern to construct complex security objects through method chaining.
3
4
## Core Security Builders
5
6
### HttpSecurity
7
8
The primary builder for configuring HTTP security policies and filter chains.
9
10
```java { .api }
11
public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain, HttpSecurity>
12
implements SecurityBuilder<DefaultSecurityFilterChain>, HttpSecurityBuilder<HttpSecurity> {
13
14
// Authorization Configuration
15
public AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry authorizeHttpRequests();
16
public ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests();
17
18
// Authentication Configuration
19
public FormLoginConfigurer<HttpSecurity> formLogin();
20
public FormLoginConfigurer<HttpSecurity> formLogin(Customizer<FormLoginConfigurer<HttpSecurity>> formLoginCustomizer);
21
public HttpBasicConfigurer<HttpSecurity> httpBasic();
22
public HttpBasicConfigurer<HttpSecurity> httpBasic(Customizer<HttpBasicConfigurer<HttpSecurity>> httpBasicCustomizer);
23
public OAuth2LoginConfigurer<HttpSecurity> oauth2Login();
24
public OAuth2LoginConfigurer<HttpSecurity> oauth2Login(Customizer<OAuth2LoginConfigurer<HttpSecurity>> oauth2LoginCustomizer);
25
public Saml2LoginConfigurer<HttpSecurity> saml2Login();
26
public Saml2LoginConfigurer<HttpSecurity> saml2Login(Customizer<Saml2LoginConfigurer<HttpSecurity>> saml2LoginCustomizer);
27
public X509Configurer<HttpSecurity> x509();
28
public X509Configurer<HttpSecurity> x509(Customizer<X509Configurer<HttpSecurity>> x509Customizer);
29
public JeeConfigurer<HttpSecurity> jee();
30
public JeeConfigurer<HttpSecurity> jee(Customizer<JeeConfigurer<HttpSecurity>> jeeCustomizer);
31
public RememberMeConfigurer<HttpSecurity> rememberMe();
32
public RememberMeConfigurer<HttpSecurity> rememberMe(Customizer<RememberMeConfigurer<HttpSecurity>> rememberMeCustomizer);
33
public AnonymousConfigurer<HttpSecurity> anonymous();
34
public AnonymousConfigurer<HttpSecurity> anonymous(Customizer<AnonymousConfigurer<HttpSecurity>> anonymousCustomizer);
35
36
// Session Management
37
public SessionManagementConfigurer<HttpSecurity> sessionManagement();
38
public SessionManagementConfigurer<HttpSecurity> sessionManagement(Customizer<SessionManagementConfigurer<HttpSecurity>> sessionManagementCustomizer);
39
public SecurityContextConfigurer<HttpSecurity> securityContext();
40
public SecurityContextConfigurer<HttpSecurity> securityContext(Customizer<SecurityContextConfigurer<HttpSecurity>> securityContextCustomizer);
41
42
// Security Protection
43
public CsrfConfigurer<HttpSecurity> csrf();
44
public CsrfConfigurer<HttpSecurity> csrf(Customizer<CsrfConfigurer<HttpSecurity>> csrfCustomizer);
45
public CorsConfigurer<HttpSecurity> cors();
46
public CorsConfigurer<HttpSecurity> cors(Customizer<CorsConfigurer<HttpSecurity>> corsCustomizer);
47
public HeadersConfigurer<HttpSecurity> headers();
48
public HeadersConfigurer<HttpSecurity> headers(Customizer<HeadersConfigurer<HttpSecurity>> headersCustomizer);
49
public ExceptionHandlingConfigurer<HttpSecurity> exceptionHandling();
50
public ExceptionHandlingConfigurer<HttpSecurity> exceptionHandling(Customizer<ExceptionHandlingConfigurer<HttpSecurity>> exceptionHandlingCustomizer);
51
52
// Logout Configuration
53
public LogoutConfigurer<HttpSecurity> logout();
54
public LogoutConfigurer<HttpSecurity> logout(Customizer<LogoutConfigurer<HttpSecurity>> logoutCustomizer);
55
public OidcLogoutConfigurer<HttpSecurity> oidcLogout();
56
public OidcLogoutConfigurer<HttpSecurity> oidcLogout(Customizer<OidcLogoutConfigurer<HttpSecurity>> oidcLogoutCustomizer);
57
58
// OAuth2 Configuration
59
public OAuth2ClientConfigurer<HttpSecurity> oauth2Client();
60
public OAuth2ClientConfigurer<HttpSecurity> oauth2Client(Customizer<OAuth2ClientConfigurer<HttpSecurity>> oauth2ClientCustomizer);
61
public OAuth2ResourceServerConfigurer<HttpSecurity> oauth2ResourceServer();
62
public OAuth2ResourceServerConfigurer<HttpSecurity> oauth2ResourceServer(Customizer<OAuth2ResourceServerConfigurer<HttpSecurity>> oauth2ResourceServerCustomizer);
63
64
// Modern Authentication
65
public OneTimeTokenLoginConfigurer<HttpSecurity> oneTimeTokenLogin();
66
public OneTimeTokenLoginConfigurer<HttpSecurity> oneTimeTokenLogin(Customizer<OneTimeTokenLoginConfigurer<HttpSecurity>> oneTimeTokenLoginCustomizer);
67
public WebAuthnConfigurer<HttpSecurity> webAuthn(Customizer<WebAuthnConfigurer<HttpSecurity>> webAuthnCustomizer);
68
69
// Filter Management
70
public HttpSecurity addFilter(Filter filter);
71
public HttpSecurity addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter);
72
public HttpSecurity addFilterAfter(Filter filter, Class<? extends Filter> afterFilter);
73
public HttpSecurity addFilterAt(Filter filter, Class<? extends Filter> atFilter);
74
75
// Security Infrastructure
76
public HttpSecurity authenticationManager(AuthenticationManager authenticationManager);
77
public HttpSecurity authenticationProvider(AuthenticationProvider authenticationProvider);
78
public HttpSecurity userDetailsService(UserDetailsService userDetailsService);
79
80
// Request Matching
81
public HttpSecurity securityMatchers(Customizer<RequestMatcherConfigurer> requestMatcherCustomizer);
82
public HttpSecurity securityMatcher(String pattern);
83
public HttpSecurity securityMatcher(RequestMatcher requestMatcher);
84
85
// Build Configuration
86
public DefaultSecurityFilterChain build() throws Exception;
87
}
88
```
89
90
**Usage Example:**
91
92
```java
93
@Bean
94
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
95
return http
96
.authorizeHttpRequests(authz -> authz
97
.requestMatchers("/admin/**").hasRole("ADMIN")
98
.requestMatchers("/user/**").hasRole("USER")
99
.anyRequest().authenticated()
100
)
101
.formLogin(form -> form
102
.loginPage("/login")
103
.defaultSuccessUrl("/dashboard")
104
.failureUrl("/login?error")
105
)
106
.logout(logout -> logout
107
.logoutUrl("/logout")
108
.logoutSuccessUrl("/login?logout")
109
.invalidateHttpSession(true)
110
)
111
.sessionManagement(session -> session
112
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
113
.maximumSessions(1)
114
.maxSessionsPreventsLogin(false)
115
)
116
.csrf(csrf -> csrf
117
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
118
)
119
.build();
120
}
121
```
122
123
### WebSecurity
124
125
Global web security configuration builder for application-wide settings.
126
127
```java { .api }
128
public final class WebSecurity extends AbstractConfiguredSecurityBuilder<Filter, WebSecurity>
129
implements SecurityBuilder<Filter> {
130
131
// Ignoring Configuration
132
public IgnoredRequestConfigurer ignoring();
133
134
// Firewall Configuration
135
public WebSecurity httpFirewall(HttpFirewall httpFirewall);
136
137
// Debugging
138
public WebSecurity debug(boolean debugEnabled);
139
140
// Security Evaluation
141
public WebSecurity privilegeEvaluator(WebInvocationPrivilegeEvaluator privilegeEvaluator);
142
public WebSecurity expressionHandler(SecurityExpressionHandler<FilterInvocation> expressionHandler);
143
144
// Filter Chain Management
145
public WebSecurity addSecurityFilterChainBuilder(SecurityBuilder<? extends SecurityFilterChain> securityFilterChainBuilder);
146
147
// Request Rejection Handling
148
public WebSecurity requestRejectedHandler(RequestRejectedHandler requestRejectedHandler);
149
150
// Post-Build Actions
151
public WebSecurity postBuildAction(Runnable postBuildAction);
152
153
// Build Configuration
154
public Filter build() throws Exception;
155
}
156
```
157
158
**Usage Example:**
159
160
```java
161
@Bean
162
public WebSecurityCustomizer webSecurityCustomizer() {
163
return (web) -> web
164
.ignoring()
165
.requestMatchers("/css/**", "/js/**", "/images/**", "/webjars/**")
166
.and()
167
.debug(false)
168
.httpFirewall(new StrictHttpFirewall());
169
}
170
```
171
172
### AuthenticationManagerBuilder
173
174
Builder for configuring AuthenticationManager with multiple authentication providers.
175
176
```java { .api }
177
public class AuthenticationManagerBuilder
178
extends AbstractConfiguredSecurityBuilder<AuthenticationManager, AuthenticationManagerBuilder>
179
implements ProviderManagerBuilder<AuthenticationManagerBuilder> {
180
181
// User Details Services
182
public InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemoryAuthentication() throws Exception;
183
public JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcAuthentication() throws Exception;
184
public LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> ldapAuthentication() throws Exception;
185
186
// Custom Authentication
187
public DaoAuthenticationConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManager> userDetailsService(UserDetailsService userDetailsService) throws Exception;
188
public AuthenticationManagerBuilder authenticationProvider(AuthenticationProvider authenticationProvider);
189
190
// Parent Authentication Manager
191
public AuthenticationManagerBuilder parentAuthenticationManager(AuthenticationManager authenticationManager);
192
193
// Authentication Events
194
public AuthenticationManagerBuilder authenticationEventPublisher(AuthenticationEventPublisher eventPublisher);
195
196
// Security Configuration
197
public AuthenticationManagerBuilder eraseCredentials(boolean eraseCredentials);
198
199
// Build Configuration
200
public AuthenticationManager build() throws Exception;
201
}
202
```
203
204
**Usage Example:**
205
206
```java
207
@Bean
208
public AuthenticationManager authenticationManager(
209
UserDetailsService userDetailsService,
210
PasswordEncoder passwordEncoder) throws Exception {
211
212
AuthenticationManagerBuilder authenticationManagerBuilder =
213
new AuthenticationManagerBuilder(objectPostProcessor);
214
215
return authenticationManagerBuilder
216
.userDetailsService(userDetailsService)
217
.passwordEncoder(passwordEncoder)
218
.and()
219
.authenticationProvider(customAuthenticationProvider())
220
.build();
221
}
222
```
223
224
### RSocketSecurity
225
226
RSocket security configuration builder for reactive messaging.
227
228
```java { .api }
229
public class RSocketSecurity {
230
231
// Authorization Configuration
232
public AuthorizePayloadsSpec authorizePayload(Customizer<AuthorizePayloadsSpec> payloadsSpecCustomizer);
233
234
// Authentication Configuration
235
public RSocketSecurity simpleAuthentication(Customizer<SimpleAuthenticationSpec> simpleAuthenticationCustomizer);
236
public RSocketSecurity jwt(Customizer<JwtSpec> jwtCustomizer);
237
public RSocketSecurity basicAuthentication(Customizer<BasicAuthenticationSpec> basicAuthenticationCustomizer);
238
239
// Build Configuration
240
public PayloadSocketAcceptorInterceptor build();
241
}
242
```
243
244
**Usage Example:**
245
246
```java
247
@Bean
248
public PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
249
return rsocket
250
.authorizePayload(authorize -> authorize
251
.setup().hasRole("SETUP")
252
.route("user.find").hasRole("USER")
253
.route("admin.*").hasRole("ADMIN")
254
.anyRequest().authenticated()
255
)
256
.jwt(jwt -> jwt
257
.authenticationManager(jwtAuthenticationManager())
258
)
259
.build();
260
}
261
```
262
263
## Base Builder Infrastructure
264
265
### SecurityBuilder Interface
266
267
Base interface for all security builders.
268
269
```java { .api }
270
public interface SecurityBuilder<O> {
271
/**
272
* Builds the object and returns it or null.
273
* @return the built object or null if the implementation allows it
274
* @throws Exception if an error occurred when building the Object
275
*/
276
O build() throws Exception;
277
}
278
```
279
280
### SecurityConfigurer Interface
281
282
Interface for configuring SecurityBuilder instances.
283
284
```java { .api }
285
public interface SecurityConfigurer<O, B extends SecurityBuilder<O>> {
286
/**
287
* Initialize the SecurityBuilder.
288
* @param builder the SecurityBuilder to use
289
* @throws Exception if an error occurs
290
*/
291
void init(B builder) throws Exception;
292
293
/**
294
* Configure the SecurityBuilder by modifying the SecurityBuilder.
295
* @param builder the SecurityBuilder to modify
296
* @throws Exception if an error occurs
297
*/
298
void configure(B builder) throws Exception;
299
}
300
```
301
302
### SecurityConfigurerAdapter
303
304
Base adapter class providing common configurer functionality.
305
306
```java { .api }
307
public abstract class SecurityConfigurerAdapter<O, B extends SecurityBuilder<O>>
308
implements SecurityConfigurer<O, B> {
309
310
private B securityBuilder;
311
private CompositeObjectPostProcessor objectPostProcessor = new CompositeObjectPostProcessor();
312
313
public void init(B builder) throws Exception {}
314
315
public void configure(B builder) throws Exception {}
316
317
/**
318
* Return the SecurityBuilder when done using the SecurityConfigurer.
319
* @return the SecurityBuilder for further customizations
320
*/
321
public B and() {
322
return getBuilder();
323
}
324
325
/**
326
* Gets the SecurityBuilder and automatically applies the ObjectPostProcessor.
327
*/
328
protected final B getBuilder() {
329
if (securityBuilder == null) {
330
throw new IllegalStateException("securityBuilder cannot be null");
331
}
332
return securityBuilder;
333
}
334
335
/**
336
* Performs post processing of an object using the ObjectPostProcessor.
337
* @param object the Object to post process
338
* @return the possibly modified Object to use
339
*/
340
protected final <T> T postProcess(T object) {
341
return (T) objectPostProcessor.postProcess(object);
342
}
343
344
/**
345
* Sets the SecurityBuilder to be used.
346
*/
347
@SuppressWarnings("unchecked")
348
public void setBuilder(B builder) {
349
this.securityBuilder = builder;
350
}
351
}
352
```
353
354
## Builder Configuration Patterns
355
356
### Method Chaining
357
358
All builders support fluent method chaining for readable configuration:
359
360
```java
361
http
362
.authorizeHttpRequests(authz -> authz.anyRequest().authenticated())
363
.formLogin(form -> form.loginPage("/login"))
364
.logout(logout -> logout.logoutSuccessUrl("/"))
365
.sessionManagement(session -> session.maximumSessions(1))
366
.build();
367
```
368
369
### Customizer Pattern
370
371
Builders use the Customizer functional interface for configuration:
372
373
```java
374
http.formLogin(formLogin -> {
375
formLogin
376
.loginPage("/custom-login")
377
.usernameParameter("email")
378
.passwordParameter("pass")
379
.defaultSuccessUrl("/dashboard", true);
380
});
381
```
382
383
### Default Configuration
384
385
Use `Customizer.withDefaults()` for default configurations:
386
387
```java
388
http
389
.formLogin(Customizer.withDefaults())
390
.httpBasic(Customizer.withDefaults())
391
.oauth2Login(Customizer.withDefaults());
392
```
393
394
### Conditional Configuration
395
396
Apply configuration conditionally based on environment or other factors:
397
398
```java
399
if (environment.acceptsProfiles(Profiles.of("development"))) {
400
http.csrf(csrf -> csrf.disable());
401
}
402
403
// Or using method references
404
http.csrf(isDevelopment() ? CsrfConfigurer::disable : Customizer.withDefaults());
405
```