0
# Access Control and Authorization
1
2
Spring Security Web's access control framework provides comprehensive authorization mechanisms, exception handling, and privilege evaluation for web resources. It handles access denied scenarios and integrates with authorization managers to enforce security policies.
3
4
## Core Access Control Components
5
6
### Access Denied Handling
7
8
Access denied handlers define how to respond when access is denied to authenticated users.
9
10
```java { .api }
11
public interface AccessDeniedHandler {
12
// Handle access denied scenarios
13
void handle(HttpServletRequest request, HttpServletResponse response,
14
AccessDeniedException accessDeniedException) throws IOException, ServletException;
15
}
16
```
17
18
### Exception Translation
19
20
The `ExceptionTranslationFilter` converts security exceptions into appropriate HTTP responses.
21
22
```java { .api }
23
public class ExceptionTranslationFilter extends GenericFilterBean {
24
// Constructors
25
public ExceptionTranslationFilter(AuthenticationEntryPoint authenticationEntryPoint);
26
public ExceptionTranslationFilter(AuthenticationEntryPoint authenticationEntryPoint,
27
RequestCache requestCache);
28
29
// Configuration methods
30
public void setAccessDeniedHandler(AccessDeniedHandler accessDeniedHandler);
31
public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint);
32
public void setRequestCache(RequestCache requestCache);
33
public void setAuthenticationTrustResolver(AuthenticationTrustResolver authenticationTrustResolver);
34
public void setThrowableAnalyzer(ThrowableAnalyzer throwableAnalyzer);
35
36
// Filter implementation
37
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
38
throws IOException, ServletException;
39
}
40
```
41
42
## Access Denied Handlers
43
44
### Default Access Denied Handler
45
46
Forwards to an error page when access is denied.
47
48
```java { .api }
49
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
50
// Constructor
51
public AccessDeniedHandlerImpl();
52
53
// Configuration
54
public void setErrorPage(String errorPage);
55
56
// AccessDeniedHandler implementation
57
public void handle(HttpServletRequest request, HttpServletResponse response,
58
AccessDeniedException accessDeniedException) throws IOException, ServletException;
59
}
60
```
61
62
### HTTP Status Access Denied Handler
63
64
Returns an HTTP status code when access is denied.
65
66
```java { .api }
67
public class HttpStatusAccessDeniedHandler implements AccessDeniedHandler {
68
// Constructor
69
public HttpStatusAccessDeniedHandler(HttpStatus httpStatus);
70
71
// AccessDeniedHandler implementation
72
public void handle(HttpServletRequest request, HttpServletResponse response,
73
AccessDeniedException accessDeniedException) throws IOException, ServletException;
74
}
75
```
76
77
### Delegating Access Denied Handler
78
79
Delegates to different handlers based on request characteristics or exception types.
80
81
```java { .api }
82
public class DelegatingAccessDeniedHandler implements AccessDeniedHandler {
83
// Constructor
84
public DelegatingAccessDeniedHandler(Map<Class<? extends AccessDeniedException>, AccessDeniedHandler> handlers,
85
AccessDeniedHandler defaultHandler);
86
87
// AccessDeniedHandler implementation
88
public void handle(HttpServletRequest request, HttpServletResponse response,
89
AccessDeniedException accessDeniedException) throws IOException, ServletException;
90
}
91
92
public class RequestMatcherDelegatingAccessDeniedHandler implements AccessDeniedHandler {
93
// Constructor
94
public RequestMatcherDelegatingAccessDeniedHandler(Map<RequestMatcher, AccessDeniedHandler> handlers,
95
AccessDeniedHandler defaultHandler);
96
97
// AccessDeniedHandler implementation
98
public void handle(HttpServletRequest request, HttpServletResponse response,
99
AccessDeniedException accessDeniedException) throws IOException, ServletException;
100
}
101
```
102
103
### Usage Examples
104
105
```java
106
// Forward to error page
107
AccessDeniedHandlerImpl pageHandler = new AccessDeniedHandlerImpl();
108
pageHandler.setErrorPage("/access-denied");
109
110
// Return 403 status
111
HttpStatusAccessDeniedHandler statusHandler =
112
new HttpStatusAccessDeniedHandler(HttpStatus.FORBIDDEN);
113
114
// Different handlers for different request types
115
Map<RequestMatcher, AccessDeniedHandler> handlerMap = Map.of(
116
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"), statusHandler,
117
new MediaTypeRequestMatcher(MediaType.APPLICATION_JSON), statusHandler
118
);
119
120
RequestMatcherDelegatingAccessDeniedHandler delegatingHandler =
121
new RequestMatcherDelegatingAccessDeniedHandler(handlerMap, pageHandler);
122
123
// Configure exception translation filter
124
ExceptionTranslationFilter exceptionFilter = new ExceptionTranslationFilter(authenticationEntryPoint);
125
exceptionFilter.setAccessDeniedHandler(delegatingHandler);
126
```
127
128
## Web Invocation Privilege Evaluator
129
130
Evaluates whether access should be allowed to web resources.
131
132
```java { .api }
133
public interface WebInvocationPrivilegeEvaluator {
134
// Check access to URI
135
boolean isAllowed(String uri, Authentication authentication);
136
137
// Check access to HTTP request
138
boolean isAllowed(HttpServletRequest request, Authentication authentication);
139
}
140
```
141
142
### Default Implementation
143
144
```java { .api }
145
public class DefaultWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator {
146
// Constructor
147
public DefaultWebInvocationPrivilegeEvaluator(FilterInvocationSecurityMetadataSource securityMetadataSource,
148
AuthenticationManager authenticationManager,
149
AccessDecisionManager accessDecisionManager);
150
151
// WebInvocationPrivilegeEvaluator implementation
152
public boolean isAllowed(String uri, Authentication authentication);
153
public boolean isAllowed(HttpServletRequest request, Authentication authentication);
154
}
155
```
156
157
### Authorization Manager Based Implementation
158
159
```java { .api }
160
public final class AuthorizationManagerWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator {
161
// Constructor
162
public AuthorizationManagerWebInvocationPrivilegeEvaluator(AuthorizationManager<RequestAuthorizationContext> authorizationManager);
163
164
// WebInvocationPrivilegeEvaluator implementation
165
public boolean isAllowed(String uri, Authentication authentication);
166
public boolean isAllowed(HttpServletRequest request, Authentication authentication);
167
}
168
```
169
170
### Usage Example
171
172
```java
173
// Check if user can access specific URLs
174
WebInvocationPrivilegeEvaluator evaluator = new AuthorizationManagerWebInvocationPrivilegeEvaluator(
175
authorizationManager
176
);
177
178
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
179
180
// Check access to specific URI
181
boolean canAccessAdmin = evaluator.isAllowed("/admin/users", auth);
182
boolean canAccessProfile = evaluator.isAllowed("/profile", auth);
183
184
// Check access to current request
185
boolean canAccessCurrent = evaluator.isAllowed(request, auth);
186
```
187
188
## IP Address Authorization
189
190
Authorizes requests based on IP address patterns.
191
192
```java { .api }
193
public final class IpAddressAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
194
// Static factory methods
195
public static IpAddressAuthorizationManager hasIpAddress(String ipAddress);
196
public static IpAddressAuthorizationManager hasIpAddressRange(String ipAddressRange);
197
198
// AuthorizationManager implementation
199
public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context);
200
}
201
```
202
203
### Usage Example
204
205
```java
206
// Allow access only from specific IP ranges
207
AuthorizationManager<RequestAuthorizationContext> ipAuth =
208
IpAddressAuthorizationManager.hasIpAddress("192.168.1.0/24")
209
.or(IpAddressAuthorizationManager.hasIpAddress("10.0.0.0/8"));
210
211
// Configure in security chain
212
http.authorizeHttpRequests(auth -> auth
213
.requestMatchers("/admin/**").access(ipAuth)
214
.anyRequest().authenticated()
215
);
216
```
217
218
## Request Transformers
219
220
Transform requests for authorization processing.
221
222
```java { .api }
223
public final class HandlerMappingIntrospectorRequestTransformer implements AuthorizationManagerRequestTransformer {
224
// Constructor
225
public HandlerMappingIntrospectorRequestTransformer(HandlerMappingIntrospector handlerMappingIntrospector);
226
227
// AuthorizationManagerRequestTransformer implementation
228
public HttpServletRequest transform(HttpServletRequest request);
229
}
230
231
public final class PathPatternRequestTransformer implementsAuthorizationManagerRequestTransformer {
232
// Static factory method
233
public static PathPatternRequestTransformer pathPattern();
234
235
// AuthorizationManagerRequestTransformer implementation
236
public HttpServletRequest transform(HttpServletRequest request);
237
}
238
```
239
240
## Composite and Delegating Handlers
241
242
### Composite Access Denied Handler
243
244
Executes multiple access denied handlers in sequence.
245
246
```java { .api }
247
public class CompositeAccessDeniedHandler implements AccessDeniedHandler {
248
// Constructor
249
public CompositeAccessDeniedHandler(AccessDeniedHandler... accessDeniedHandlers);
250
public CompositeAccessDeniedHandler(List<AccessDeniedHandler> accessDeniedHandlers);
251
252
// AccessDeniedHandler implementation
253
public void handle(HttpServletRequest request, HttpServletResponse response,
254
AccessDeniedException accessDeniedException) throws IOException, ServletException;
255
}
256
```
257
258
### Usage Example
259
260
```java
261
// Execute multiple handlers for access denied
262
CompositeAccessDeniedHandler composite = new CompositeAccessDeniedHandler(
263
new AuditAccessDeniedHandler(), // Log the access denial
264
new MetricsAccessDeniedHandler(), // Record metrics
265
new HttpStatusAccessDeniedHandler(HttpStatus.FORBIDDEN) // Return response
266
);
267
```
268
269
## Exception Translation Patterns
270
271
### Basic Exception Translation
272
273
```java
274
// Basic setup for web applications
275
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(
276
new LoginUrlAuthenticationEntryPoint("/login")
277
);
278
filter.setAccessDeniedHandler(new AccessDeniedHandlerImpl("/access-denied"));
279
```
280
281
### API Exception Translation
282
283
```java
284
// Setup for REST APIs
285
ExceptionTranslationFilter apiFilter = new ExceptionTranslationFilter(
286
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)
287
);
288
apiFilter.setAccessDeniedHandler(new HttpStatusAccessDeniedHandler(HttpStatus.FORBIDDEN));
289
```
290
291
### Mixed Application Exception Translation
292
293
```java
294
// Different handling for web vs API requests
295
Map<RequestMatcher, AccessDeniedHandler> accessDeniedHandlers = Map.of(
296
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"),
297
new HttpStatusAccessDeniedHandler(HttpStatus.FORBIDDEN),
298
299
new MediaTypeRequestMatcher(MediaType.APPLICATION_JSON),
300
new HttpStatusAccessDeniedHandler(HttpStatus.FORBIDDEN)
301
);
302
303
RequestMatcherDelegatingAccessDeniedHandler delegating =
304
new RequestMatcherDelegatingAccessDeniedHandler(
305
accessDeniedHandlers,
306
new AccessDeniedHandlerImpl("/access-denied")
307
);
308
309
Map<RequestMatcher, AuthenticationEntryPoint> entryPoints = Map.of(
310
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"),
311
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
312
313
new MediaTypeRequestMatcher(MediaType.APPLICATION_JSON),
314
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)
315
);
316
317
DelegatingAuthenticationEntryPoint delegatingEntry =
318
new DelegatingAuthenticationEntryPoint(entryPoints);
319
delegatingEntry.setDefaultEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));
320
321
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(delegatingEntry);
322
filter.setAccessDeniedHandler(delegating);
323
```
324
325
## Error Handling
326
327
Common exceptions in access control:
328
329
- **AccessDeniedException**: Thrown when authenticated user lacks required permissions
330
- **AuthenticationException**: Thrown when user is not authenticated
331
- **InsufficientAuthenticationException**: Thrown when authentication level is insufficient
332
- **AuthenticationServiceException**: Thrown for authentication service errors
333
334
The `ExceptionTranslationFilter` catches these exceptions and converts them to appropriate HTTP responses based on the configured handlers.