Filters
A filter runs around every request, before the handler is even looked up. Declare a bean that implements WebFilter; the starter runs every such bean in @Order, then the handler.
Why
Some work concerns all requests rather than one endpoint:
- a request id in every answer and log line;
- access logs and timing;
- checking a token, an API key or an IP range, and refusing early;
- adding security headers;
- wrapping the request (another path, a principal) or the response (counting bytes).
A filter sees every request: those that end in a controller, in a static file, in a 404, or in a CORS pre-flight. The security starter's filter chain is one such filter.
For work tied to the controllers, with the chosen method at hand or its result, a HandlerInterceptor fits better. See WebMvcConfigurer.
Example
import 'dart:math';
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
const log = SpringLog('app.web');
// Every answer carries an id the logs can be searched by.
@Component()
@Order(Ordered.highestPrecedence + 100)
class RequestIdFilter implements WebFilter {
final _random = Random();
@override
Future<void> doFilter(
ServerHttpRequest request,
ServerHttpResponse response,
WebFilterChain chain,
) {
final id = request.headers['X-Request-Id'] ??
_random.nextInt(1 << 32).toRadixString(16);
request.attributes['requestId'] = id;
response.headers.set('X-Request-Id', id);
return chain.doFilter(request, response);
}
}
// Requests are timed, except the load balancer's health checks.
@Component()
class TimingFilter extends OncePerRequestFilter {
@override
bool shouldNotFilter(ServerHttpRequest request) => request.path == '/health';
@override
Future<void> doFilterInternal(
ServerHttpRequest request,
ServerHttpResponse response,
WebFilterChain chain,
) async {
final watch = Stopwatch()..start();
try {
await chain.doFilter(request, response);
} finally {
log.info('${request.method.value} ${request.path} '
'${response.statusCode} in ${watch.elapsedMilliseconds} ms');
}
}
}
// A filter that answers by itself: no key, no service.
@Component()
@Order(10)
class ApiKeyFilter extends OncePerRequestFilter {
ApiKeyFilter(@Value(r'${shop.api-key}') this.key);
final String key;
@override
bool shouldNotFilter(ServerHttpRequest request) =>
!request.path.startsWith('/api/');
@override
Future<void> doFilterInternal(
ServerHttpRequest request,
ServerHttpResponse response,
WebFilterChain chain,
) async {
if (request.headers['X-Api-Key'] != key) {
// The chain is not called: the controller never runs.
await response.send(401, 'Missing or wrong API key');
return;
}
await chain.doFilter(request, response);
}
}
WebFilter
| Member | Meaning |
|---|---|
Future<void> doFilter(ServerHttpRequest request, ServerHttpResponse response, WebFilterChain chain) |
Handles the request. Call chain.doFilter(request, response) to pass it on, with the same objects or wrapped ones. Or answer through response and return without calling the chain. |
WebFilterChain |
Meaning |
|---|---|
Future<void> doFilter(ServerHttpRequest request, ServerHttpResponse response) |
Runs the next filter, or after the last one the handler, and completes when they are done. |
Rules:
- Code before
chain.doFilterruns on the way in; code after it (once itsFuturecompleted) runs on the way out, when the handler has written its answer. To change the response's headers, do it before the chain: once the body has started, they are sent. - Await or return the chain's
Future. A filter that does neither lets the request run on unwatched, and its errors are lost. - Not calling the chain stops the request at the filter. Answer it then (
response.send(status, text), or write andclose()). - An exception thrown by a filter skips the
@ExceptionHandlermethods and theHandlerExceptionResolverbeans, and gets the default error answer, aProblemDetail. - An exception of the handler is first offered to the
@ExceptionHandlermethods and the resolvers, inside the chain. When one of them answers it, the filters see a finished error response. When none does, the exception comes out ofchain.doFilter, passes through the filters (atry/finallysees it), and is answered with the defaultProblemDetailat the end. - A filter is a bean, so it can inject other beans and properties.
OncePerRequestFilter
A base class for a filter that does its work at most once per request and can leave some requests alone. Extend it rather than implementing WebFilter when a filter should skip some paths.
| Member | Meaning |
|---|---|
bool shouldNotFilter(ServerHttpRequest request) |
Whether the request passes this filter untouched. false by default. Override it to exclude paths or methods. |
Future<void> doFilterInternal(request, response, chain) |
The filter's work, called instead of doFilter for the requests it handles. |
It marks the request with the attribute <ClassName>.FILTERED. When the same request passes the filters again (a filter that calls a chain twice, a forward of your own), the second pass goes straight on down the chain.
Order
Filters run in the order of their beans, lowest first:
@Order(n)on the class, or the class implementsOrdered(int get order).Ordered.highestPrecedence(the smallestint) runs first. A filter without an order runs last (Ordered.lowestPrecedence), after every ordered one.- Use offsets (
Ordered.highestPrecedence + 100) or small numbers, and leave room between them.
The built-in filters:
| Filter | Order | Present when | Does |
|---|---|---|---|
RequestRateFilter |
Ordered.highestPrecedence |
the build has the debug feature qps (spring.web.debug.qps.enabled: true) |
Counts the requests of its isolate and how long each took, around every other filter. See Requests per second. |
ForwardedHeaderFilter |
-10000 |
server.forward-headers-strategy is native or framework |
Applies Forwarded / X-Forwarded-* from trusted proxies: scheme, host, port, client address. See Behind a reverse proxy. |
The actuator's WebEndpointRequestFilter |
-5000 |
the actuator starter is used | Its own requests. |
HttpSessionFilter |
-1000 |
always | Finds the request's session, so request.getSession() works in every later filter. See Sessions. |
The security starter's filter chain (FilterChainProxy) |
-100 (spring.security.filter.order) |
the security starter is used | Authentication, authorization, CSRF, CORS, security headers. |
Choose your filter's place by what it needs:
- needs the client's real address or scheme: after
-10000; - uses the session: after
-1000; - needs the logged-in user (
request.principal): after-100; - must see every request, even those the security chain refuses (an access log): before
-100.
Wrapping the request or the response
A filter can pass other objects down the chain. ServerHttpRequestDecorator and ServerHttpResponseDecorator forward every member to the object they wrap; override only what changes.
// Requests to /v1/... are handled as /api/... .
final class _Renamed extends ServerHttpRequestDecorator {
_Renamed(super.delegate, this.path);
@override
final String path;
}
// Counts the bytes of every answer.
final class _Counting extends ServerHttpResponseDecorator {
_Counting(super.delegate);
var bytes = 0;
@override
void add(List<int> data) {
bytes += data.length;
super.add(data);
}
@override
void write(String text) => add(utf8.encode(text));
}
@Component()
class LegacyPathFilter implements WebFilter {
@override
Future<void> doFilter(request, response, chain) async {
final path = request.path.startsWith('/v1/')
? '/api/${request.path.substring(4)}'
: request.path;
final counting = _Counting(response);
await chain.doFilter(_Renamed(request, path), counting);
log.debug('${counting.bytes} bytes for $path');
}
}
(utf8 comes from dart:convert.)
What a request offers: method, uri, path (without the context path), headers, queryParameters, cookies, remoteAddress, isSecure, attributes (a map for the request's lifetime), principal, body, contentType. A response: statusCode, headers, addCookie, isCommitted, add, write, flush, addStream, close, done, and send(status, text).
Where a filter runs
For each request, the dispatcher:
- runs the request in its own
Zone, soRequestContextHolder.currentRequestis the request anywhere in its handling, acrossawaits; withserver.request-timeout, under the request's deadline too; - removes
server.context-pathfrom the path (a request outside it is a404, before any filter); - runs the filters, in order;
- asks the handler mappings for a handler, in their order: the controllers (
0), the WebSocket endpoints (1), the static resources (last); none is a404; - answers exceptions of the handler through the
@ExceptionHandlermethods and the resolvers.
So a filter sees request.path without the context path, and runs for every request inside it, whatever ends up answering.
// Any code that runs for the request can find it, without a parameter.
@Service()
class AuditLog {
void record(String action) {
final request = RequestContextHolder.currentRequest;
log.info('$action by ${request?.principal?.name ?? 'anonymous'} '
'(${request?.attributes['requestId']})');
}
}
In Spring (Java)
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
class RequestIdFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
response.setHeader("X-Request-Id", newId());
chain.doFilter(request, response);
}
}
Differences that matter:
- A filter is a
WebFilterbean with one asynchronous method, closer to WebFlux'sWebFilterthan to a servletFilter. - There is no
FilterRegistrationBean: a filter applies to every request. Restrict it withshouldNotFilter. - Wrappers are
ServerHttpRequestDecoratorandServerHttpResponseDecorator, notHttpServletRequestWrapper. RequestContextHolder.currentRequestfollows the request acrossawaits through aZone, not a thread-local.- An exception thrown by a filter gets the default error answer;
@ExceptionHandlermethods do not see it, as in Spring.
See also
- WebMvcConfigurer: interceptors
- Sessions
- CORS
- Behind a reverse proxy
- Handler mappings
- @Component