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 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:

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:

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:

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:

  1. runs the request in its own Zone, so RequestContextHolder.currentRequest is the request anywhere in its handling, across awaits; with server.request-timeout, under the request's deadline too;
  2. removes server.context-path from the path (a request outside it is a 404, before any filter);
  3. runs the filters, in order;
  4. asks the handler mappings for a handler, in their order: the controllers (0), the WebSocket endpoints (1), the static resources (last); none is a 404;
  5. answers exceptions of the handler through the @ExceptionHandler methods 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:

See also