0
# Authentication Framework
1
2
Spring Security Web's authentication framework provides comprehensive mechanisms for user authentication, including form-based login, HTTP Basic authentication, and extensible authentication processing. The framework is built around pluggable authentication handlers, converters, and entry points.
3
4
## Core Authentication Components
5
6
### Authentication Handlers
7
8
Authentication handlers define what happens after authentication attempts succeed or fail.
9
10
```java { .api }
11
public interface AuthenticationSuccessHandler {
12
// Called when authentication succeeds
13
void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
14
Authentication authentication) throws IOException, ServletException;
15
16
// Called when authentication succeeds with filter chain continuation
17
default void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
18
FilterChain chain, Authentication authentication)
19
throws IOException, ServletException;
20
}
21
22
public interface AuthenticationFailureHandler {
23
// Called when authentication fails
24
void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
25
AuthenticationException exception) throws IOException, ServletException;
26
}
27
```
28
29
### Authentication Entry Points
30
31
Entry points define how to commence authentication when it's required.
32
33
```java { .api }
34
public interface AuthenticationEntryPoint {
35
// Commences authentication (e.g., redirect to login page, return 401)
36
void commence(HttpServletRequest request, HttpServletResponse response,
37
AuthenticationException authException) throws IOException, ServletException;
38
}
39
```
40
41
## Form-Based Authentication
42
43
### Username Password Authentication Filter
44
45
The primary filter for handling form-based login.
46
47
```java { .api }
48
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
49
// Default parameter names
50
public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
51
public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
52
53
// Configuration methods
54
public void setUsernameParameter(String usernameParameter);
55
public void setPasswordParameter(String passwordParameter);
56
public void setPostOnly(boolean postOnly);
57
58
// Authentication processing
59
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
60
throws AuthenticationException;
61
}
62
```
63
64
### Usage Example
65
66
```java
67
// Configure form-based authentication
68
UsernamePasswordAuthenticationFilter authFilter = new UsernamePasswordAuthenticationFilter();
69
authFilter.setAuthenticationManager(authenticationManager);
70
71
// Custom parameter names
72
authFilter.setUsernameParameter("email");
73
authFilter.setPasswordParameter("pwd");
74
75
// Custom login URL
76
authFilter.setRequiresAuthenticationRequestMatcher(
77
new AntPathRequestMatcher("/custom-login", "POST")
78
);
79
80
// Success handler - redirect to dashboard
81
authFilter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/dashboard"));
82
83
// Failure handler - return to login with error
84
authFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login?error"));
85
```
86
87
## Authentication Success Handlers
88
89
### Simple URL Success Handler
90
91
Redirects to a configured URL on successful authentication.
92
93
```java { .api }
94
public class SimpleUrlAuthenticationSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler
95
implements AuthenticationSuccessHandler {
96
97
// Constructors
98
public SimpleUrlAuthenticationSuccessHandler();
99
public SimpleUrlAuthenticationSuccessHandler(String defaultTargetUrl);
100
101
// Configuration
102
public void setDefaultTargetUrl(String defaultTargetUrl);
103
public void setAlwaysUseDefaultTargetUrl(boolean alwaysUseDefaultTargetUrl);
104
public void setTargetUrlParameter(String targetUrlParameter);
105
106
// AuthenticationSuccessHandler implementation
107
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
108
Authentication authentication) throws IOException, ServletException;
109
}
110
```
111
112
### Saved Request Aware Success Handler
113
114
Redirects to originally requested URL after authentication.
115
116
```java { .api }
117
public class SavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
118
// Configuration
119
public void setRequestCache(RequestCache requestCache);
120
public void setTargetUrlParameter(String targetUrlParameter);
121
122
// Handles redirect to saved request or default URL
123
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
124
Authentication authentication) throws IOException, ServletException;
125
}
126
```
127
128
### Additional Success Handlers
129
130
```java { .api }
131
public class ForwardAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
132
// Constructor
133
public ForwardAuthenticationSuccessHandler(String forwardUrl);
134
135
// AuthenticationSuccessHandler implementation
136
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
137
Authentication authentication) throws IOException, ServletException;
138
}
139
140
public class HttpMessageConverterAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
141
// Constructor
142
public HttpMessageConverterAuthenticationSuccessHandler();
143
144
// Configuration
145
public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters);
146
147
// AuthenticationSuccessHandler implementation
148
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
149
Authentication authentication) throws IOException, ServletException;
150
}
151
```
152
153
### Usage Example
154
155
```java
156
// Redirect to originally requested page
157
SavedRequestAwareAuthenticationSuccessHandler successHandler =
158
new SavedRequestAwareAuthenticationSuccessHandler();
159
successHandler.setDefaultTargetUrl("/dashboard");
160
successHandler.setTargetUrlParameter("continue");
161
162
// Always redirect to specific URL
163
SimpleUrlAuthenticationSuccessHandler simpleHandler =
164
new SimpleUrlAuthenticationSuccessHandler("/admin/welcome");
165
simpleHandler.setAlwaysUseDefaultTargetUrl(true);
166
```
167
168
## Authentication Failure Handlers
169
170
### Simple URL Failure Handler
171
172
Redirects to a configured URL on authentication failure.
173
174
```java { .api }
175
public class SimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler {
176
// Constructors
177
public SimpleUrlAuthenticationFailureHandler();
178
public SimpleUrlAuthenticationFailureHandler(String defaultFailureUrl);
179
180
// Configuration
181
public void setDefaultFailureUrl(String defaultFailureUrl);
182
public void setAllowSessionCreation(boolean allowSessionCreation);
183
public void setUseForward(boolean forwardToDestination);
184
185
// AuthenticationFailureHandler implementation
186
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
187
AuthenticationException exception) throws IOException, ServletException;
188
}
189
```
190
191
### Exception Mapping Failure Handler
192
193
Maps different exception types to different failure URLs.
194
195
```java { .api }
196
public class ExceptionMappingAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
197
// Configure exception to URL mappings
198
public void setExceptionMappings(Properties exceptionMappings);
199
200
// Map specific exception to URL
201
public void setDefaultFailureUrl(String defaultFailureUrl);
202
}
203
```
204
205
### Additional Failure Handlers
206
207
```java { .api }
208
public class ForwardAuthenticationFailureHandler implements AuthenticationFailureHandler {
209
// Constructor
210
public ForwardAuthenticationFailureHandler(String forwardUrl);
211
212
// AuthenticationFailureHandler implementation
213
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
214
AuthenticationException exception) throws IOException, ServletException;
215
}
216
217
public class DelegatingAuthenticationFailureHandler implements AuthenticationFailureHandler {
218
// Constructor
219
public DelegatingAuthenticationFailureHandler(
220
LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> handlers,
221
AuthenticationFailureHandler defaultHandler);
222
223
// AuthenticationFailureHandler implementation
224
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
225
AuthenticationException exception) throws IOException, ServletException;
226
}
227
228
public class AuthenticationEntryPointFailureHandler implements AuthenticationFailureHandler {
229
// Constructor
230
public AuthenticationEntryPointFailureHandler(AuthenticationEntryPoint authenticationEntryPoint);
231
232
// AuthenticationFailureHandler implementation
233
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
234
AuthenticationException exception) throws IOException, ServletException;
235
}
236
```
237
238
### Usage Example
239
240
```java
241
// Map different exceptions to different error pages
242
ExceptionMappingAuthenticationFailureHandler failureHandler =
243
new ExceptionMappingAuthenticationFailureHandler();
244
245
Properties mappings = new Properties();
246
mappings.put("org.springframework.security.authentication.BadCredentialsException",
247
"/login?error=invalid");
248
mappings.put("org.springframework.security.authentication.DisabledException",
249
"/login?error=disabled");
250
mappings.put("org.springframework.security.authentication.LockedException",
251
"/login?error=locked");
252
253
failureHandler.setExceptionMappings(mappings);
254
failureHandler.setDefaultFailureUrl("/login?error=unknown");
255
```
256
257
## Authentication Entry Points
258
259
### Login URL Entry Point
260
261
Redirects unauthenticated users to a login page.
262
263
```java { .api }
264
public class LoginUrlAuthenticationEntryPoint implements AuthenticationEntryPoint {
265
// Constructors
266
public LoginUrlAuthenticationEntryPoint(String loginFormUrl);
267
268
// Configuration
269
public void setForceHttps(boolean forceHttps);
270
public void setUseForward(boolean useForward);
271
public void setPortMapper(PortMapper portMapper);
272
public void setPortResolver(PortResolver portResolver);
273
274
// AuthenticationEntryPoint implementation
275
public void commence(HttpServletRequest request, HttpServletResponse response,
276
AuthenticationException authException) throws IOException, ServletException;
277
}
278
```
279
280
### HTTP Status Entry Point
281
282
Returns an HTTP status code instead of redirecting.
283
284
```java { .api }
285
public class HttpStatusEntryPoint implements AuthenticationEntryPoint {
286
// Constructor
287
public HttpStatusEntryPoint(HttpStatus httpStatus);
288
289
// AuthenticationEntryPoint implementation
290
public void commence(HttpServletRequest request, HttpServletResponse response,
291
AuthenticationException authException) throws IOException, ServletException;
292
}
293
```
294
295
### Additional Entry Points
296
297
```java { .api }
298
public class Http403ForbiddenEntryPoint implements AuthenticationEntryPoint {
299
// AuthenticationEntryPoint implementation
300
public void commence(HttpServletRequest request, HttpServletResponse response,
301
AuthenticationException authException) throws IOException, ServletException;
302
}
303
304
public class NoOpAuthenticationEntryPoint implements AuthenticationEntryPoint {
305
// AuthenticationEntryPoint implementation
306
public void commence(HttpServletRequest request, HttpServletResponse response,
307
AuthenticationException authException) throws IOException, ServletException;
308
}
309
```
310
311
### Delegating Entry Point
312
313
Delegates to different entry points based on request matching.
314
315
```java { .api }
316
public class DelegatingAuthenticationEntryPoint implements AuthenticationEntryPoint {
317
// Constructor
318
public DelegatingAuthenticationEntryPoint(LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints);
319
320
// Configuration
321
public void setDefaultEntryPoint(AuthenticationEntryPoint defaultEntryPoint);
322
323
// AuthenticationEntryPoint implementation
324
public void commence(HttpServletRequest request, HttpServletResponse response,
325
AuthenticationException authException) throws IOException, ServletException;
326
}
327
```
328
329
### Usage Example
330
331
```java
332
// Redirect to login page
333
LoginUrlAuthenticationEntryPoint loginEntry = new LoginUrlAuthenticationEntryPoint("/login");
334
loginEntry.setForceHttps(true);
335
loginEntry.setUseForward(false);
336
337
// Return 401 for API endpoints
338
HttpStatusEntryPoint apiEntry = new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
339
340
// Delegating entry point based on request type
341
DelegatingAuthenticationEntryPoint delegatingEntry = new DelegatingAuthenticationEntryPoint(
342
Map.of(
343
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"), apiEntry,
344
new MediaTypeRequestMatcher(MediaType.APPLICATION_JSON), apiEntry
345
)
346
);
347
delegatingEntry.setDefaultEntryPoint(loginEntry);
348
```
349
350
## Authentication Converters
351
352
Authentication converters extract authentication information from HTTP requests.
353
354
```java { .api }
355
public interface AuthenticationConverter {
356
// Convert request to Authentication object
357
Authentication convert(HttpServletRequest request);
358
}
359
360
public class DelegatingAuthenticationConverter implements AuthenticationConverter {
361
// Constructor
362
public DelegatingAuthenticationConverter(List<AuthenticationConverter> delegates);
363
364
// AuthenticationConverter implementation
365
public Authentication convert(HttpServletRequest request);
366
}
367
```
368
369
### Authentication Manager Resolver
370
371
Resolves authentication managers based on request characteristics.
372
373
```java { .api }
374
public class RequestMatcherDelegatingAuthenticationManagerResolver
375
implements AuthenticationManagerResolver<HttpServletRequest> {
376
377
// Constructor
378
public RequestMatcherDelegatingAuthenticationManagerResolver(
379
LinkedHashMap<RequestMatcher, AuthenticationManager> authenticationManagers);
380
381
// Configuration
382
public void setDefaultAuthenticationManager(AuthenticationManager defaultAuthenticationManager);
383
384
// AuthenticationManagerResolver implementation
385
public AuthenticationManager resolve(HttpServletRequest request);
386
}
387
```
388
389
## Anonymous Authentication
390
391
Provides anonymous authentication when no other authentication is present.
392
393
```java { .api }
394
public class AnonymousAuthenticationFilter extends GenericFilterBean {
395
// Constructors
396
public AnonymousAuthenticationFilter(String key);
397
public AnonymousAuthenticationFilter(String key, Object principal,
398
Collection<? extends GrantedAuthority> authorities);
399
400
// Filter implementation
401
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
402
throws IOException, ServletException;
403
}
404
```
405
406
### Usage Example
407
408
```java
409
// Configure anonymous authentication
410
AnonymousAuthenticationFilter anonymousFilter = new AnonymousAuthenticationFilter(
411
"anonymousKey",
412
"anonymousUser",
413
List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))
414
);
415
```
416
417
## Web Authentication Details
418
419
Captures additional web-specific authentication information.
420
421
```java { .api }
422
public class WebAuthenticationDetails implements Serializable {
423
// Constructor
424
public WebAuthenticationDetails(HttpServletRequest request);
425
426
// Access methods
427
public String getRemoteAddress();
428
public String getSessionId();
429
}
430
431
public class WebAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> {
432
// AuthenticationDetailsSource implementation
433
public WebAuthenticationDetails buildDetails(HttpServletRequest context);
434
}
435
```
436
437
## Remember-Me Authentication
438
439
Provides persistent login functionality across browser sessions.
440
441
```java { .api }
442
public interface RememberMeServices {
443
// Attempt automatic login
444
Authentication autoLogin(HttpServletRequest request, HttpServletResponse response);
445
446
// Handle login failure
447
void loginFail(HttpServletRequest request, HttpServletResponse response);
448
449
// Handle login success
450
void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication);
451
}
452
```
453
454
## Logout Framework
455
456
Spring Security provides comprehensive logout functionality to handle user logout and session cleanup.
457
458
### Logout Filter
459
460
The main filter that handles logout requests.
461
462
```java { .api }
463
public class LogoutFilter extends GenericFilterBean {
464
// Constructor
465
public LogoutFilter(String logoutSuccessUrl, LogoutHandler... handlers);
466
public LogoutFilter(LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers);
467
468
// Configuration
469
public void setFilterProcessesUrl(String filterProcessesUrl);
470
public void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher);
471
472
// Filter implementation
473
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
474
throws IOException, ServletException;
475
}
476
```
477
478
### Logout Handlers
479
480
Handle various logout tasks such as clearing security context and invalidating sessions.
481
482
```java { .api }
483
public interface LogoutHandler {
484
// Perform logout operations
485
void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication);
486
}
487
488
public class SecurityContextLogoutHandler implements LogoutHandler {
489
// Configuration
490
public void setInvalidateHttpSession(boolean invalidateHttpSession);
491
public void setClearAuthentication(boolean clearAuthentication);
492
493
// LogoutHandler implementation
494
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication);
495
}
496
497
public class CookieClearingLogoutHandler implements LogoutHandler {
498
// Constructor
499
public CookieClearingLogoutHandler(String... cookiesToClear);
500
501
// LogoutHandler implementation
502
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication);
503
}
504
505
public class HeaderWriterLogoutHandler implements LogoutHandler {
506
// Constructor
507
public HeaderWriterLogoutHandler(HeaderWriter... headerWriters);
508
509
// LogoutHandler implementation
510
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication);
511
}
512
```
513
514
### Logout Success Handlers
515
516
Define what happens after successful logout.
517
518
```java { .api }
519
public interface LogoutSuccessHandler {
520
// Handle successful logout
521
void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
522
Authentication authentication) throws IOException, ServletException;
523
}
524
525
public class SimpleUrlLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler
526
implements LogoutSuccessHandler {
527
528
// Constructor
529
public SimpleUrlLogoutSuccessHandler();
530
531
// Configuration
532
public void setDefaultTargetUrl(String defaultTargetUrl);
533
534
// LogoutSuccessHandler implementation
535
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
536
Authentication authentication) throws IOException, ServletException;
537
}
538
539
public class HttpStatusReturningLogoutSuccessHandler implements LogoutSuccessHandler {
540
// Constructor
541
public HttpStatusReturningLogoutSuccessHandler(HttpStatus httpStatusToReturn);
542
543
// LogoutSuccessHandler implementation
544
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
545
Authentication authentication) throws IOException, ServletException;
546
}
547
```
548
549
### Usage Example
550
551
```java
552
// Basic logout configuration
553
List<LogoutHandler> handlers = Arrays.asList(
554
new SecurityContextLogoutHandler(),
555
new CookieClearingLogoutHandler("JSESSIONID", "remember-me")
556
);
557
558
LogoutFilter logoutFilter = new LogoutFilter("/login?logout", handlers.toArray(new LogoutHandler[0]));
559
logoutFilter.setFilterProcessesUrl("/logout");
560
561
// Custom logout success handler
562
SimpleUrlLogoutSuccessHandler successHandler = new SimpleUrlLogoutSuccessHandler();
563
successHandler.setDefaultTargetUrl("/goodbye");
564
565
LogoutFilter customLogout = new LogoutFilter(successHandler, handlers.toArray(new LogoutHandler[0]));
566
```
567
568
## Common Authentication Patterns
569
570
### Basic Web Application
571
572
```java
573
// Complete authentication setup for web application
574
UsernamePasswordAuthenticationFilter authFilter = new UsernamePasswordAuthenticationFilter();
575
authFilter.setAuthenticationManager(authenticationManager);
576
authFilter.setAuthenticationSuccessHandler(
577
new SavedRequestAwareAuthenticationSuccessHandler()
578
);
579
authFilter.setAuthenticationFailureHandler(
580
new SimpleUrlAuthenticationFailureHandler("/login?error")
581
);
582
583
AnonymousAuthenticationFilter anonymousFilter = new AnonymousAuthenticationFilter("key");
584
585
List<Filter> filters = Arrays.asList(
586
new SecurityContextHolderFilter(repository),
587
authFilter,
588
anonymousFilter
589
);
590
```
591
592
### API with Custom Authentication
593
594
```java
595
// Custom authentication converter for API keys
596
AuthenticationConverter apiKeyConverter = request -> {
597
String apiKey = request.getHeader("X-API-Key");
598
return apiKey != null ? new ApiKeyAuthenticationToken(apiKey) : null;
599
};
600
601
AuthenticationFilter apiFilter = new AuthenticationFilter(
602
authenticationManager,
603
apiKeyConverter
604
);
605
apiFilter.setSuccessHandler((req, res, chain, auth) -> chain.doFilter(req, res));
606
apiFilter.setFailureHandler(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
607
```