0
# Authentication Configuration
1
2
Spring Security Config provides comprehensive authentication configuration capabilities through builders and configurers that support various authentication mechanisms including in-memory, JDBC, LDAP, and custom authentication providers.
3
4
## AuthenticationManagerBuilder
5
6
The primary builder for configuring AuthenticationManager instances with multiple authentication providers.
7
8
```java { .api }
9
public class AuthenticationManagerBuilder
10
extends AbstractConfiguredSecurityBuilder<AuthenticationManager, AuthenticationManagerBuilder>
11
implements ProviderManagerBuilder<AuthenticationManagerBuilder> {
12
13
// User Details Services Configuration
14
public InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemoryAuthentication() throws Exception;
15
public JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcAuthentication() throws Exception;
16
public LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> ldapAuthentication() throws Exception;
17
18
// Custom User Details Service
19
public DaoAuthenticationConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManager> userDetailsService(UserDetailsService userDetailsService) throws Exception;
20
21
// Custom Authentication Provider
22
public AuthenticationManagerBuilder authenticationProvider(AuthenticationProvider authenticationProvider);
23
24
// Parent Authentication Manager
25
public AuthenticationManagerBuilder parentAuthenticationManager(AuthenticationManager authenticationManager);
26
27
// Authentication Event Publisher
28
public AuthenticationManagerBuilder authenticationEventPublisher(AuthenticationEventPublisher eventPublisher);
29
30
// Security Configuration
31
public AuthenticationManagerBuilder eraseCredentials(boolean eraseCredentials);
32
33
// Build Configuration
34
public AuthenticationManager build() throws Exception;
35
}
36
```
37
38
**Usage Example:**
39
40
```java
41
@Bean
42
public AuthenticationManager authenticationManager(
43
UserDetailsService userDetailsService,
44
PasswordEncoder passwordEncoder) throws Exception {
45
46
return new AuthenticationManagerBuilder(objectPostProcessor)
47
.userDetailsService(userDetailsService)
48
.passwordEncoder(passwordEncoder)
49
.and()
50
.authenticationProvider(customAuthenticationProvider())
51
.parentAuthenticationManager(globalAuthenticationManager())
52
.build();
53
}
54
```
55
56
## User Details Service Configurers
57
58
### InMemoryUserDetailsManagerConfigurer
59
60
Configuration for in-memory user storage and authentication.
61
62
```java { .api }
63
public class InMemoryUserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>>
64
extends UserDetailsManagerConfigurer<B, InMemoryUserDetailsManagerConfigurer<B>> {
65
66
// User Creation
67
public UserDetailsBuilder withUser(String username);
68
public InMemoryUserDetailsManagerConfigurer<B> withUser(UserDetails userDetails);
69
70
// Password Encoder
71
public InMemoryUserDetailsManagerConfigurer<B> passwordEncoder(PasswordEncoder passwordEncoder);
72
73
// User Details Builder
74
public final class UserDetailsBuilder {
75
public UserDetailsBuilder password(String password);
76
public UserDetailsBuilder roles(String... roles);
77
public UserDetailsBuilder authorities(String... authorities);
78
public UserDetailsBuilder authorities(GrantedAuthority... authorities);
79
public UserDetailsBuilder accountExpired(boolean accountExpired);
80
public UserDetailsBuilder accountLocked(boolean accountLocked);
81
public UserDetailsBuilder credentialsExpired(boolean credentialsExpired);
82
public UserDetailsBuilder disabled(boolean disabled);
83
public UserDetails build();
84
public InMemoryUserDetailsManagerConfigurer<B> and();
85
}
86
}
87
```
88
89
**Usage Example:**
90
91
```java
92
@Bean
93
public AuthenticationManager authenticationManager() throws Exception {
94
return new AuthenticationManagerBuilder(objectPostProcessor)
95
.inMemoryAuthentication()
96
.passwordEncoder(passwordEncoder())
97
.withUser("admin")
98
.password("admin123")
99
.roles("ADMIN", "USER")
100
.and()
101
.withUser("user")
102
.password("user123")
103
.roles("USER")
104
.accountExpired(false)
105
.credentialsExpired(false)
106
.disabled(false)
107
.accountLocked(false)
108
.and()
109
.and()
110
.build();
111
}
112
```
113
114
### JdbcUserDetailsManagerConfigurer
115
116
Configuration for JDBC-based user storage and authentication.
117
118
```java { .api }
119
public class JdbcUserDetailsManagerConfigurer<B extends ProviderManagerBuilder<B>>
120
extends UserDetailsServiceConfigurer<B, JdbcUserDetailsManagerConfigurer<B>, JdbcUserDetailsManager> {
121
122
// Data Source Configuration
123
public JdbcUserDetailsManagerConfigurer<B> dataSource(DataSource dataSource);
124
125
// Query Configuration
126
public JdbcUserDetailsManagerConfigurer<B> usersByUsernameQuery(String query);
127
public JdbcUserDetailsManagerConfigurer<B> authoritiesByUsernameQuery(String query);
128
public JdbcUserDetailsManagerConfigurer<B> groupAuthoritiesByUsername(String query);
129
130
// Role and Authority Configuration
131
public JdbcUserDetailsManagerConfigurer<B> rolePrefix(String rolePrefix);
132
public JdbcUserDetailsManagerConfigurer<B> usernameParameter(String usernameParameter);
133
134
// Password Encoder
135
public JdbcUserDetailsManagerConfigurer<B> passwordEncoder(PasswordEncoder passwordEncoder);
136
137
// User Details Service
138
public JdbcUserDetailsManagerConfigurer<B> userDetailsService(JdbcUserDetailsManager userDetailsService);
139
140
// User Creation
141
public UserDetailsBuilder withUser(String username);
142
public JdbcUserDetailsManagerConfigurer<B> withUser(UserDetails user);
143
144
// Default User Creation
145
public JdbcUserDetailsManagerConfigurer<B> withDefaultSchema();
146
}
147
```
148
149
**Usage Example:**
150
151
```java
152
@Bean
153
public AuthenticationManager authenticationManager(DataSource dataSource) throws Exception {
154
return new AuthenticationManagerBuilder(objectPostProcessor)
155
.jdbcAuthentication()
156
.dataSource(dataSource)
157
.passwordEncoder(passwordEncoder())
158
.usersByUsernameQuery("SELECT username, password, enabled FROM users WHERE username = ?")
159
.authoritiesByUsernameQuery("SELECT username, authority FROM authorities WHERE username = ?")
160
.rolePrefix("ROLE_")
161
.withDefaultSchema()
162
.withUser("admin")
163
.password("admin123")
164
.roles("ADMIN")
165
.and()
166
.and()
167
.build();
168
}
169
```
170
171
### DaoAuthenticationConfigurer
172
173
Configuration for DAO-based authentication with custom UserDetailsService.
174
175
```java { .api }
176
public class DaoAuthenticationConfigurer<B extends ProviderManagerBuilder<B>, U extends UserDetailsService>
177
extends UserDetailsServiceConfigurer<B, DaoAuthenticationConfigurer<B, U>, U> {
178
179
// User Details Service
180
public DaoAuthenticationConfigurer<B, U> userDetailsService(U userDetailsService);
181
182
// Password Encoder
183
public DaoAuthenticationConfigurer<B, U> passwordEncoder(PasswordEncoder passwordEncoder);
184
185
// User Details Password Service
186
public DaoAuthenticationConfigurer<B, U> userDetailsPasswordService(UserDetailsPasswordService userDetailsPasswordService);
187
}
188
```
189
190
**Usage Example:**
191
192
```java
193
@Bean
194
public AuthenticationManager authenticationManager(
195
UserDetailsService userDetailsService,
196
PasswordEncoder passwordEncoder) throws Exception {
197
198
return new AuthenticationManagerBuilder(objectPostProcessor)
199
.userDetailsService(userDetailsService)
200
.passwordEncoder(passwordEncoder)
201
.userDetailsPasswordService(userDetailsPasswordService())
202
.and()
203
.build();
204
}
205
```
206
207
## LDAP Authentication Configuration
208
209
### LdapAuthenticationProviderConfigurer
210
211
Configuration for LDAP-based authentication.
212
213
```java { .api }
214
public class LdapAuthenticationProviderConfigurer<B extends ProviderManagerBuilder<B>>
215
extends AbstractLdapAuthenticationProviderConfigurer<B, LdapAuthenticationProviderConfigurer<B>> {
216
217
// Context Source Configuration
218
public LdapAuthenticationProviderConfigurer<B> contextSource(BaseLdapPathContextSource contextSource);
219
220
// User Search Configuration
221
public LdapAuthenticationProviderConfigurer<B> userSearchBase(String userSearchBase);
222
public LdapAuthenticationProviderConfigurer<B> userSearchFilter(String userSearchFilter);
223
public LdapAuthenticationProviderConfigurer<B> userDnPatterns(String... userDnPatterns);
224
225
// Group Search Configuration
226
public LdapAuthenticationProviderConfigurer<B> groupSearchBase(String groupSearchBase);
227
public LdapAuthenticationProviderConfigurer<B> groupSearchFilter(String groupSearchFilter);
228
public LdapAuthenticationProviderConfigurer<B> groupRoleAttribute(String groupRoleAttribute);
229
230
// Authentication Strategy Configuration
231
public PasswordComparisonConfigurer<LdapAuthenticationProviderConfigurer<B>> passwordCompare();
232
public BindAuthenticatorConfigurer<LdapAuthenticationProviderConfigurer<B>> bindAuthentication();
233
234
// Role and Authority Configuration
235
public LdapAuthenticationProviderConfigurer<B> rolePrefix(String rolePrefix);
236
public LdapAuthenticationProviderConfigurer<B> userDetailsContextMapper(UserDetailsContextMapper userDetailsContextMapper);
237
238
// Nested Configuration Classes
239
public final class PasswordComparisonConfigurer<T> {
240
public PasswordComparisonConfigurer<T> passwordEncoder(PasswordEncoder passwordEncoder);
241
public PasswordComparisonConfigurer<T> passwordAttribute(String passwordAttribute);
242
public T and();
243
}
244
245
public final class BindAuthenticatorConfigurer<T> {
246
public T and();
247
}
248
}
249
```
250
251
**Usage Example:**
252
253
```java
254
@Bean
255
public AuthenticationManager authenticationManager() throws Exception {
256
return new AuthenticationManagerBuilder(objectPostProcessor)
257
.ldapAuthentication()
258
.userDnPatterns("uid={0},ou=people")
259
.userSearchBase("ou=people")
260
.userSearchFilter("(uid={0})")
261
.groupSearchBase("ou=groups")
262
.groupSearchFilter("(uniqueMember={0})")
263
.groupRoleAttribute("cn")
264
.rolePrefix("ROLE_")
265
.contextSource(contextSource())
266
.passwordCompare()
267
.passwordEncoder(passwordEncoder())
268
.passwordAttribute("userPassword")
269
.and()
270
.and()
271
.build();
272
}
273
274
@Bean
275
public BaseLdapPathContextSource contextSource() {
276
DefaultSpringSecurityContextSource contextSource =
277
new DefaultSpringSecurityContextSource("ldap://localhost:389/dc=example,dc=com");
278
contextSource.setUserDn("cn=admin,dc=example,dc=com");
279
contextSource.setPassword("admin");
280
return contextSource;
281
}
282
```
283
284
## Authentication Infrastructure
285
286
### AuthenticationConfiguration
287
288
Global authentication configuration providing AuthenticationManager beans.
289
290
```java { .api }
291
@Configuration
292
@Import(ObjectPostProcessorConfiguration.class)
293
public class AuthenticationConfiguration {
294
295
// Authentication Manager Bean
296
@Bean
297
public AuthenticationManager authenticationManager() throws Exception;
298
299
// Authentication Manager Builder
300
@Bean
301
public AuthenticationManagerBuilder authenticationManagerBuilder(
302
ObjectPostProcessor<Object> objectPostProcessor,
303
ApplicationContext context);
304
305
// Global Authentication Configurer Adapter
306
@Bean
307
public static GlobalAuthenticationConfigurerAdapter enableGlobalAuthenticationAutowiredConfigurer(
308
ApplicationContext context);
309
310
// Authentication Event Publisher
311
@Bean
312
public DefaultAuthenticationEventPublisher authenticationEventPublisher(ApplicationEventPublisher publisher);
313
}
314
```
315
316
### GlobalAuthenticationConfigurerAdapter
317
318
Base class for configuring global authentication.
319
320
```java { .api }
321
public abstract class GlobalAuthenticationConfigurerAdapter implements SecurityConfigurer<AuthenticationManager, AuthenticationManagerBuilder> {
322
323
public void init(AuthenticationManagerBuilder auth) throws Exception {}
324
325
public void configure(AuthenticationManagerBuilder auth) throws Exception {}
326
}
327
```
328
329
**Usage Example:**
330
331
```java
332
@Configuration
333
public class CustomAuthenticationConfig extends GlobalAuthenticationConfigurerAdapter {
334
335
@Autowired
336
private UserDetailsService userDetailsService;
337
338
@Autowired
339
private PasswordEncoder passwordEncoder;
340
341
@Override
342
public void configure(AuthenticationManagerBuilder auth) throws Exception {
343
auth.userDetailsService(userDetailsService)
344
.passwordEncoder(passwordEncoder);
345
}
346
}
347
```
348
349
## Custom Authentication Providers
350
351
### Creating Custom Authentication Providers
352
353
Implement custom authentication logic by creating AuthenticationProvider implementations.
354
355
```java { .api }
356
public interface AuthenticationProvider {
357
/**
358
* Performs authentication with the same contract as AuthenticationManager.
359
* @param authentication the authentication request object
360
* @return a fully authenticated object including credentials
361
* @throws AuthenticationException if authentication fails
362
*/
363
Authentication authenticate(Authentication authentication) throws AuthenticationException;
364
365
/**
366
* Returns true if this AuthenticationProvider supports the indicated
367
* Authentication object.
368
* @param authentication the Authentication class
369
* @return true if the implementation can process the Authentication class
370
*/
371
boolean supports(Class<?> authentication);
372
}
373
```
374
375
**Custom Provider Example:**
376
377
```java
378
@Component
379
public class CustomAuthenticationProvider implements AuthenticationProvider {
380
381
@Autowired
382
private UserDetailsService userDetailsService;
383
384
@Autowired
385
private PasswordEncoder passwordEncoder;
386
387
@Override
388
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
389
String username = authentication.getName();
390
String password = authentication.getCredentials().toString();
391
392
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
393
394
if (passwordEncoder.matches(password, userDetails.getPassword())) {
395
return new UsernamePasswordAuthenticationToken(
396
userDetails, password, userDetails.getAuthorities());
397
} else {
398
throw new BadCredentialsException("Authentication failed");
399
}
400
}
401
402
@Override
403
public boolean supports(Class<?> authentication) {
404
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
405
}
406
}
407
408
// Configuration
409
@Bean
410
public AuthenticationManager authenticationManager(
411
CustomAuthenticationProvider customProvider) throws Exception {
412
413
return new AuthenticationManagerBuilder(objectPostProcessor)
414
.authenticationProvider(customProvider)
415
.build();
416
}
417
```
418
419
## Password Encoding Configuration
420
421
### Password Encoder Integration
422
423
Configure password encoding for secure credential storage.
424
425
```java { .api }
426
public interface PasswordEncoder {
427
/**
428
* Encode the raw password.
429
* @param rawPassword the raw password to encode
430
* @return the encoded password
431
*/
432
String encode(CharSequence rawPassword);
433
434
/**
435
* Verify the encoded password obtained from storage matches the submitted raw password.
436
* @param rawPassword the raw password to verify
437
* @param encodedPassword the encoded password from storage
438
* @return true if the raw password matches the encoded password
439
*/
440
boolean matches(CharSequence rawPassword, String encodedPassword);
441
442
/**
443
* Returns true if the encoded password should be encoded again for better security.
444
* @param encodedPassword the encoded password to check
445
* @return true if the encoded password should be encoded again
446
*/
447
default boolean upgradeEncoding(String encodedPassword) {
448
return false;
449
}
450
}
451
```
452
453
**Password Encoder Configuration:**
454
455
```java
456
@Bean
457
public PasswordEncoder passwordEncoder() {
458
return new BCryptPasswordEncoder(12);
459
}
460
461
@Bean
462
public AuthenticationManager authenticationManager(
463
UserDetailsService userDetailsService,
464
PasswordEncoder passwordEncoder) throws Exception {
465
466
return new AuthenticationManagerBuilder(objectPostProcessor)
467
.userDetailsService(userDetailsService)
468
.passwordEncoder(passwordEncoder)
469
.and()
470
.build();
471
}
472
```
473
474
## Authentication Events
475
476
### Authentication Event Publisher
477
478
Configure authentication event publishing for monitoring and auditing.
479
480
```java { .api }
481
public interface AuthenticationEventPublisher {
482
/**
483
* Publish a successful authentication event.
484
* @param authentication the successful authentication
485
*/
486
void publishAuthenticationSuccess(Authentication authentication);
487
488
/**
489
* Publish an authentication failure event.
490
* @param exception the authentication exception
491
* @param authentication the failed authentication attempt
492
*/
493
void publishAuthenticationFailure(AuthenticationException exception, Authentication authentication);
494
}
495
```
496
497
**Event Publisher Configuration:**
498
499
```java
500
@Bean
501
public AuthenticationEventPublisher authenticationEventPublisher(
502
ApplicationEventPublisher applicationEventPublisher) {
503
return new DefaultAuthenticationEventPublisher(applicationEventPublisher);
504
}
505
506
@Bean
507
public AuthenticationManager authenticationManager(
508
AuthenticationEventPublisher eventPublisher) throws Exception {
509
510
return new AuthenticationManagerBuilder(objectPostProcessor)
511
.authenticationEventPublisher(eventPublisher)
512
.userDetailsService(userDetailsService())
513
.passwordEncoder(passwordEncoder())
514
.and()
515
.build();
516
}
517
518
@EventListener
519
public void handleAuthenticationSuccess(AuthenticationSuccessEvent event) {
520
log.info("Authentication success for user: {}", event.getAuthentication().getName());
521
}
522
523
@EventListener
524
public void handleAuthenticationFailure(AbstractAuthenticationFailureEvent event) {
525
log.warn("Authentication failure: {}", event.getException().getMessage());
526
}
527
```
528
529
## Integration Patterns
530
531
### Multi-Provider Authentication
532
533
Configure multiple authentication providers for different authentication strategies:
534
535
```java
536
@Bean
537
public AuthenticationManager authenticationManager(
538
UserDetailsService userDetailsService,
539
LdapAuthenticationProvider ldapProvider,
540
CustomAuthenticationProvider customProvider) throws Exception {
541
542
return new AuthenticationManagerBuilder(objectPostProcessor)
543
.authenticationProvider(ldapProvider)
544
.authenticationProvider(customProvider)
545
.userDetailsService(userDetailsService)
546
.passwordEncoder(passwordEncoder())
547
.and()
548
.build();
549
}
550
```
551
552
### Hierarchical Authentication Managers
553
554
Configure parent-child authentication manager relationships:
555
556
```java
557
@Bean
558
public AuthenticationManager parentAuthenticationManager() throws Exception {
559
return new AuthenticationManagerBuilder(objectPostProcessor)
560
.inMemoryAuthentication()
561
.withUser("global-admin")
562
.password("global-password")
563
.roles("GLOBAL_ADMIN")
564
.and()
565
.build();
566
}
567
568
@Bean
569
public AuthenticationManager childAuthenticationManager(
570
AuthenticationManager parentAuthenticationManager) throws Exception {
571
572
return new AuthenticationManagerBuilder(objectPostProcessor)
573
.parentAuthenticationManager(parentAuthenticationManager)
574
.userDetailsService(localUserDetailsService())
575
.passwordEncoder(passwordEncoder())
576
.and()
577
.build();
578
}
579
```
580
581
### Custom User Details Service Integration
582
583
Integrate custom user storage and retrieval logic:
584
585
```java
586
@Service
587
public class CustomUserDetailsService implements UserDetailsService {
588
589
@Autowired
590
private UserRepository userRepository;
591
592
@Override
593
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
594
User user = userRepository.findByUsername(username)
595
.orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
596
597
return User.builder()
598
.username(user.getUsername())
599
.password(user.getPassword())
600
.authorities(user.getAuthorities())
601
.accountExpired(!user.isAccountNonExpired())
602
.accountLocked(!user.isAccountNonLocked())
603
.credentialsExpired(!user.isCredentialsNonExpired())
604
.disabled(!user.isEnabled())
605
.build();
606
}
607
}
608
```