0
# Security Configuration
1
2
Spring Boot's security configuration provides comprehensive auto-configuration for Spring Security including servlet security, reactive security, OAuth2, and SAML integration.
3
4
## Capabilities
5
6
### Core Spring Security Configuration
7
8
Auto-configuration for basic Spring Security components and authentication mechanisms.
9
10
```java { .api }
11
/**
12
* Auto-configuration for Spring Security
13
* Provides basic security configuration for web applications
14
*/
15
@AutoConfiguration
16
@ConditionalOnClass({DefaultAuthenticationEventPublisher.class})
17
@EnableConfigurationProperties(SecurityProperties.class)
18
@Import({SpringBootWebSecurityConfiguration.class, WebSecurityEnablerConfiguration.class,
19
SecurityDataConfiguration.class})
20
public class SecurityAutoConfiguration {
21
22
/**
23
* Default authentication event publisher
24
*/
25
@Bean
26
@ConditionalOnMissingBean(AuthenticationEventPublisher.class)
27
public DefaultAuthenticationEventPublisher authenticationEventPublisher(ApplicationEventPublisher publisher) {
28
return new DefaultAuthenticationEventPublisher(publisher);
29
}
30
}
31
32
/**
33
* Security configuration properties
34
*/
35
@ConfigurationProperties(prefix = "spring.security")
36
public class SecurityProperties {
37
38
/**
39
* Security filter chain order
40
*/
41
public static final int BASIC_AUTH_ORDER = 2147483642;
42
public static final int IGNORED_ORDER = Integer.MIN_VALUE;
43
public static final int DEFAULT_FILTER_ORDER = SecurityProperties.BASIC_AUTH_ORDER - 5;
44
45
/**
46
* User authentication properties
47
*/
48
private final User user = new User();
49
50
/**
51
* Security filter properties
52
*/
53
private final Filter filter = new Filter();
54
55
public User getUser() { return this.user; }
56
public Filter getFilter() { return this.filter; }
57
58
/**
59
* Default user configuration for development
60
*/
61
public static class User {
62
/**
63
* Default user name
64
*/
65
private String name = "user";
66
67
/**
68
* Password for the default user
69
*/
70
private String password = UUID.randomUUID().toString();
71
72
/**
73
* Granted roles for the default user
74
*/
75
private List<String> roles = new ArrayList<>();
76
77
/**
78
* Whether the default user account is enabled
79
*/
80
private boolean passwordGenerated = true;
81
82
// Getters and setters
83
public String getName() { return this.name; }
84
public void setName(String name) { this.name = name; }
85
public String getPassword() { return this.password; }
86
public void setPassword(String password) {
87
this.password = password;
88
this.passwordGenerated = false;
89
}
90
public List<String> getRoles() { return this.roles; }
91
public void setRoles(List<String> roles) { this.roles = new ArrayList<>(roles); }
92
}
93
94
/**
95
* Security filter configuration
96
*/
97
public static class Filter {
98
/**
99
* Security filter chain order
100
*/
101
private int order = DEFAULT_FILTER_ORDER;
102
103
/**
104
* Security filter dispatcher types
105
*/
106
private Set<DispatcherType> dispatcherTypes = EnumSet.allOf(DispatcherType.class);
107
108
public int getOrder() { return this.order; }
109
public void setOrder(int order) { this.order = order; }
110
public Set<DispatcherType> getDispatcherTypes() { return this.dispatcherTypes; }
111
public void setDispatcherTypes(Set<DispatcherType> dispatcherTypes) {
112
this.dispatcherTypes = dispatcherTypes;
113
}
114
}
115
}
116
```
117
118
### Servlet Security Configuration
119
120
Auto-configuration for servlet-based web application security.
121
122
```java { .api }
123
/**
124
* Auto-configuration for servlet-based Spring Security
125
* Configures security filter chain for traditional web applications
126
*/
127
@AutoConfiguration
128
@ConditionalOnClass({SecurityFilterChain.class})
129
@ConditionalOnWebApplication(type = Type.SERVLET)
130
@EnableConfigurationProperties(SecurityProperties.class)
131
public class SecurityFilterAutoConfiguration {
132
133
/**
134
* Default security filter chain
135
*/
136
@Bean
137
@Order(SecurityProperties.BASIC_AUTH_ORDER)
138
@ConditionalOnMissingBean({WebSecurityConfigurerAdapter.class, SecurityFilterChain.class})
139
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
140
http.authorizeHttpRequests(authz -> authz.anyRequest().authenticated())
141
.formLogin(withDefaults())
142
.httpBasic(withDefaults());
143
return http.build();
144
}
145
}
146
147
/**
148
* Configuration for method-level security
149
*/
150
@Configuration(proxyBeanMethods = false)
151
@ConditionalOnClass({EnableGlobalMethodSecurity.class, GlobalMethodSecurityConfiguration.class})
152
@ConditionalOnMissingBean(GlobalMethodSecurityConfiguration.class)
153
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
154
public class MethodSecurityAutoConfiguration extends GlobalMethodSecurityConfiguration {
155
156
@Override
157
protected MethodSecurityExpressionHandler createExpressionHandler() {
158
return new DefaultMethodSecurityExpressionHandler();
159
}
160
}
161
```
162
163
### Reactive Security Configuration
164
165
Auto-configuration for reactive web application security using WebFlux.
166
167
```java { .api }
168
/**
169
* Auto-configuration for reactive Spring Security
170
* Configures security for reactive web applications
171
*/
172
@AutoConfiguration
173
@ConditionalOnClass({ReactiveSecurityContextHolder.class, ServerHttpSecurity.class})
174
@ConditionalOnWebApplication(type = Type.REACTIVE)
175
@EnableConfigurationProperties(SecurityProperties.class)
176
public class ReactiveSecurityAutoConfiguration {
177
178
/**
179
* Default reactive security web filter chain
180
*/
181
@Bean
182
@ConditionalOnMissingBean({SecurityWebFilterChain.class})
183
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
184
return http.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated())
185
.formLogin(withDefaults())
186
.httpBasic(withDefaults())
187
.build();
188
}
189
190
/**
191
* Reactive user details service
192
*/
193
@Bean
194
@ConditionalOnMissingBean({ReactiveUserDetailsService.class, UserDetailsService.class})
195
public MapReactiveUserDetailsService reactiveUserDetailsService(SecurityProperties properties) {
196
SecurityProperties.User user = properties.getUser();
197
UserDetails userDetails = User.withUsername(user.getName())
198
.password(passwordEncoder().encode(user.getPassword()))
199
.roles(StringUtils.toStringArray(user.getRoles()))
200
.build();
201
return new MapReactiveUserDetailsService(userDetails);
202
}
203
}
204
```
205
206
### OAuth2 Client Configuration
207
208
Auto-configuration for OAuth2 client functionality.
209
210
```java { .api }
211
/**
212
* Auto-configuration for OAuth2 client
213
* Configures OAuth2 authorization code flow and client credentials
214
*/
215
@AutoConfiguration
216
@ConditionalOnClass({OAuth2AuthorizationCodeGrantFilter.class, ClientRegistration.class})
217
@ConditionalOnWebApplication(type = Type.SERVLET)
218
@EnableConfigurationProperties(OAuth2ClientProperties.class)
219
@Import({OAuth2ClientRegistrationRepositoryConfiguration.class, OAuth2WebSecurityConfiguration.class})
220
public class OAuth2ClientAutoConfiguration {
221
222
/**
223
* OAuth2 authorized client service
224
*/
225
@Bean
226
@ConditionalOnMissingBean
227
public OAuth2AuthorizedClientService authorizedClientService(
228
ClientRegistrationRepository clientRegistrationRepository,
229
OAuth2AuthorizedClientRepository authorizedClientRepository) {
230
if (authorizedClientRepository instanceof JdbcOAuth2AuthorizedClientRepository) {
231
return new JdbcOAuth2AuthorizedClientService(
232
((JdbcOAuth2AuthorizedClientRepository) authorizedClientRepository).getJdbcOperations(),
233
clientRegistrationRepository);
234
}
235
return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
236
}
237
}
238
239
/**
240
* OAuth2 client properties
241
*/
242
@ConfigurationProperties(prefix = "spring.security.oauth2.client")
243
public class OAuth2ClientProperties {
244
245
/**
246
* OAuth2 client registrations
247
*/
248
private final Map<String, Registration> registration = new HashMap<>();
249
250
/**
251
* OAuth2 provider configurations
252
*/
253
private final Map<String, Provider> provider = new HashMap<>();
254
255
public Map<String, Registration> getRegistration() { return this.registration; }
256
public Map<String, Provider> getProvider() { return this.provider; }
257
258
/**
259
* OAuth2 client registration configuration
260
*/
261
public static class Registration {
262
/**
263
* Client identifier
264
*/
265
private String clientId;
266
267
/**
268
* Client secret
269
*/
270
private String clientSecret;
271
272
/**
273
* Client authentication method
274
*/
275
private String clientAuthenticationMethod;
276
277
/**
278
* Authorization grant type
279
*/
280
private String authorizationGrantType;
281
282
/**
283
* Redirect URI
284
*/
285
private String redirectUri;
286
287
/**
288
* Client scopes
289
*/
290
private Set<String> scope = new LinkedHashSet<>();
291
292
/**
293
* Client name
294
*/
295
private String clientName;
296
297
/**
298
* Provider identifier
299
*/
300
private String provider;
301
302
// Getters and setters
303
public String getClientId() { return this.clientId; }
304
public void setClientId(String clientId) { this.clientId = clientId; }
305
public String getClientSecret() { return this.clientSecret; }
306
public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; }
307
}
308
309
/**
310
* OAuth2 provider configuration
311
*/
312
public static class Provider {
313
/**
314
* Authorization endpoint URI
315
*/
316
private String authorizationUri;
317
318
/**
319
* Token endpoint URI
320
*/
321
private String tokenUri;
322
323
/**
324
* User info endpoint URI
325
*/
326
private String userInfoUri;
327
328
/**
329
* User name attribute name
330
*/
331
private String userNameAttribute;
332
333
/**
334
* JWK Set URI for JWT validation
335
*/
336
private String jwkSetUri;
337
338
/**
339
* Issuer identifier
340
*/
341
private String issuerUri;
342
343
// Getters and setters
344
public String getAuthorizationUri() { return this.authorizationUri; }
345
public void setAuthorizationUri(String authorizationUri) { this.authorizationUri = authorizationUri; }
346
public String getTokenUri() { return this.tokenUri; }
347
public void setTokenUri(String tokenUri) { this.tokenUri = tokenUri; }
348
}
349
}
350
```
351
352
**Usage Examples:**
353
354
```java
355
// Custom security configuration
356
@Configuration
357
@EnableWebSecurity
358
public class SecurityConfig {
359
360
@Bean
361
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
362
http.authorizeHttpRequests(authz -> authz
363
.requestMatchers("/api/public/**").permitAll()
364
.requestMatchers("/api/admin/**").hasRole("ADMIN")
365
.anyRequest().authenticated())
366
.oauth2Login(oauth2 -> oauth2
367
.loginPage("/oauth2/authorization/google")
368
.defaultSuccessUrl("/dashboard", true))
369
.logout(logout -> logout
370
.logoutSuccessUrl("/login?logout")
371
.invalidateHttpSession(true));
372
return http.build();
373
}
374
375
@Bean
376
public PasswordEncoder passwordEncoder() {
377
return new BCryptPasswordEncoder();
378
}
379
}
380
381
// OAuth2 properties configuration
382
# application.yml
383
spring:
384
security:
385
oauth2:
386
client:
387
registration:
388
google:
389
client-id: your-google-client-id
390
client-secret: your-google-client-secret
391
scope: openid,profile,email
392
redirect-uri: http://localhost:8080/login/oauth2/code/google
393
authorization-grant-type: authorization_code
394
client-name: Google
395
provider:
396
google:
397
authorization-uri: https://accounts.google.com/o/oauth2/auth
398
token-uri: https://oauth2.googleapis.com/token
399
user-info-uri: https://www.googleapis.com/oauth2/v2/userinfo
400
user-name-attribute: email
401
```
402
403
## Types
404
405
### Security Configuration Types
406
407
```java { .api }
408
/**
409
* Authentication success handler interface
410
*/
411
public interface AuthenticationSuccessHandler {
412
/**
413
* Called when authentication is successful
414
* @param request the request
415
* @param response the response
416
* @param authentication the authentication object
417
*/
418
void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
419
Authentication authentication) throws IOException, ServletException;
420
}
421
422
/**
423
* Authentication failure handler interface
424
*/
425
public interface AuthenticationFailureHandler {
426
/**
427
* Called when authentication fails
428
* @param request the request
429
* @param response the response
430
* @param exception the authentication exception
431
*/
432
void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
433
AuthenticationException exception) throws IOException, ServletException;
434
}
435
436
/**
437
* User details service interface
438
*/
439
public interface UserDetailsService {
440
/**
441
* Load user details by username
442
* @param username the username
443
* @return UserDetails instance
444
* @throws UsernameNotFoundException if user not found
445
*/
446
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
447
}
448
449
/**
450
* Reactive user details service interface
451
*/
452
public interface ReactiveUserDetailsService {
453
/**
454
* Find user details by username
455
* @param username the username
456
* @return Mono containing UserDetails
457
*/
458
Mono<UserDetails> findByUsername(String username);
459
}
460
```