Become a member!

DelphiMVCFramework 3.5.0-silicon: from middleware to filters, what happens to your server?

🌐
This article is also available in other languages:
🇮🇹 Italiano  •  🇪🇸 Español  •  🇩🇪 Deutsch  •  🇫🇷 Français  •  🇧🇷 Português

DelphiMVCFramework, the open source REST and web framework for Delphi

A classic DelphiMVCFramework middleware has four methods. An HTTP filter has a single procedure. Why did I change a mechanism that had worked for years, where do the four hooks end up, in what order do you register the filters, and what happens to the server you already have in production?

For years, the way to hook code into the lifecycle of a request in DelphiMVCFramework has been middleware, with AddMiddleware. HTTP filters arrived with the 3.5 Minimal API, the one from the RC6 post. Now filters take the place of middleware wherever an equivalent exists: seventeen middleware are marked deprecated, each with its own filter. It will be in RC9 of 3.5.0-silicon.

✅ This is not a breaking change. Your current servers keep working the same way, with no changes and no problems.

In 3.5.0-silicon filters are an additional feature: the middleware stay where they are, and the compiler shows a warning for every middleware marked deprecated. The breaking change will come in 4.0, where the middleware will be removed altogether.

DelphiMVCFramework is the most popular framework of its kind on GitHub for Delphi, with over 50 contributors, and it is used in critical environments: hospitals, banks, factories, video games, ERPs with hundreds of users. That is why I decided on a soft transition, without trauma.

In this article I talk about the two kinds of filter, the ones that run before routing and the ones that run after it, and about bundles, which register them together.

In this article


Two responsibilities in one class

Until now a middleware did two things. With OnBeforeRouting and OnAfterRouting it influenced routing: it could respond before the router looked at the request, to serve a static file, issue a redirect or respond to a CORS preflight, and at the end of the request observe or modify the response, as ETag and analytics do. With OnBeforeControllerAction and OnAfterControllerAction it controlled how actions were executed. Four methods in a single class, for two different jobs.

Anyone who knows me, or has followed one of my courses, knows how much weight I give to the SOLID principles. Finding a class with two jobs in my most popular open source project really bothered me. Every time I worked on a middleware I saw it: either you used the routing pair of methods (OnBeforeRouting and OnAfterRouting) and left the other two empty, or you implemented the endpoint pair (OnBeforeControllerAction and OnAfterControllerAction), which already knows controller and action because it runs after routing. It was obvious that this component needed refactoring. Now the time has come.

It was a violation of the single responsibility principle (SRP). I fixed it with a mechanism that exists in many frameworks: a function that receives the request and a next to call to hand over to whoever comes after. It is used by Express (next()) and Koa (await next()) in Node.js, ASP.NET Core (await next(context)) in C#, Laravel ($next($request)) in PHP, Starlette and FastAPI (call_next) in Python, Gin (c.Next()) in Go and axum (next.run(request)) in Rust.

It is the Chain of Responsibility in the variant called Intercepting Filter: each link can act before, hand over with next and act after, or stop. In DelphiMVCFramework that next is called ANext. The first responsibility goes to HTTP filters, the second to endpoint filters.


How an HTTP filter works

An HTTP filter is this procedure:

Signature of an HTTP filter: a procedure with AContext of type TWebContext and ANext of type TMVCHTTPFilterNext

Copy the code
procedure(const AContext: TWebContext; const ANext: TMVCHTTPFilterNext)

It wraps the whole request: the classic middleware, routing and the action. What you write before ANext() runs before everything else, what you write after runs when the response is complete, that is, after the action. To stop the request you don’t call ANext(), and no action is executed.

It is called HTTP because it works at the protocol level: it sees method, headers and body of the request and of the response. It works with HTTPS too, because TLS encryption sits at a lower level and the filter receives the request already decrypted.

Classic middlewareHTTP filter
InterfaceIMVCMiddleware, four methodsa procedure with AContext and ANext
Registered withAEngine.AddMiddleware(...)AEngine.Use(...)
When it runsat the four points of the cycle, in registration orderaround the whole request: classic middleware, routing and action
Before and aftertwo separate methodssame procedure: before and after ANext()
To stop the requestHandled := Trueyou don’t call ANext()
Controllersyesyes

Use is a method of TMVCEngine and returns TMVCEngine, so you can chain the calls. It is the same method for HTTP filters, endpoint filters and bundles, and the type of the argument picks the overload. That is why a filter function with no parameters needs its parentheses inside Use, ETagHTTPFilter(): without them the compiler cannot tell which overload to use (E2250). The ready-made filters are in MVCFramework.Filters, and the name tells you the kind: it ends in HTTPFilter, in EndpointFilter or, for a bundle, in Bundle.

The HTTP filter works with controllers and with the Minimal API in the same way, which is why the wizard can use the same chain in both cases. Middleware and HTTP filters are covered in chapter 14 of the official guide, second edition, endpoint filters and the Minimal API in chapter 29.


Where do the four hooks go?

  • OnBeforeRouting becomes the code before ANext().
  • OnAfterRouting becomes the code after ANext(). The name is misleading: it fires at the very end, not right after routing. If the action raises an exception, the engine handles it inside ANext() and responds with 500, and the code after ANext() still runs, just as OnAfterRouting does. A try..finally around ANext() is needed for the exceptions that come from an inner HTTP filter.
  • OnBeforeControllerAction and OnAfterControllerAction have no equivalent in an HTTP filter. They receive the name of the controller and the name of the action, which are known only after routing, while the HTTP filter wraps the whole request without knowing them. The endpoint filter (EndpointFilter), which runs after routing, has them: it is the second responsibility, and I cover it further on.

A hand-written filter

To write a filter you don’t need a class: you pass Use an anonymous method with the signature you just saw. This one adds two security headers to every response:

Hand-written HTTP filter that sets the X-Content-Type-Options and X-Frame-Options headers and then calls ANext

Copy the code
AEngine.Use(
  procedure(const AContext: TWebContext; const ANext: TMVCHTTPFilterNext)
  begin
    AContext.Response.SetCustomHeader('X-Content-Type-Options', 'nosniff');
    AContext.Response.SetCustomHeader('X-Frame-Options', 'DENY');
    ANext();
  end);

You set the headers before ANext(), so an action that wants a different value overwrites it. The ready-made SecurityHeadersHTTPFilter() filter sets X-XSS-Protection: 0 and X-Content-Type-Options: nosniff. This one is hand-written to show the shape, and it adds X-Frame-Options.

A filter can also stop the request. This one responds with 400 to POST, PUT and PATCH requests that have an empty body, or one made only of whitespace, before routing looks at them:

HTTP filter that responds with 400 to POST, PUT and PATCH requests with an empty or whitespace-only body and calls ANext only in the else branch

Copy the code
AEngine.Use(
  procedure(const AContext: TWebContext; const ANext: TMVCHTTPFilterNext)
  begin
    if (AContext.Request.HTTPMethod in [httpPOST, httpPUT, httpPATCH]) and
      AContext.Request.Body.Trim.IsEmpty then
    begin
      AContext.Response.StatusCode := HTTP_STATUS.BadRequest;
      AContext.Response.ContentType := TMVCMediaType.APPLICATION_JSON;
      AContext.Response.Content := '{"message":"The body must not be blank"}';
    end
    else
      ANext();
  end);

ANext() is in the else branch: when the filter rejects the request, ANext() is not called and no controller sees it.


The seventeen deprecated middleware

Seventeen middleware are marked deprecated: fourteen TMVC...Middleware classes and three Use...SessionMiddleware functions, which create the session middleware. Each has its own filter in MVCFramework.Filters:

Deprecated middlewareFilterHow you register it
TMVCRedirectMiddlewareRedirectHTTPFilterUse(RedirectHTTPFilter(['/'], '/web'))
TMVCStaticFilesMiddlewareStaticFilesHTTPFilterUse(StaticFilesHTTPFilter('/static', lWwwPath))
TMVCAnalyticsMiddlewareAnalyticsHTTPFilterUse(AnalyticsHTTPFilter())
TMVCTraceMiddlewareTraceHTTPFilterUse(TraceHTTPFilter())
TMVCCompressionMiddlewareCompressionHTTPFilterUse(CompressionHTTPFilter(1024))
TMVCETagMiddlewareETagHTTPFilterUse(ETagHTTPFilter())
TMVCCORSMiddlewareCORSHTTPFilterUse(CORSHTTPFilter('*'))
TMVCSecurityHeadersMiddlewareSecurityHeadersHTTPFilterUse(SecurityHeadersHTTPFilter())
TMVCShutdownMiddlewareShutdownHTTPFilterUse(ShutdownHTTPFilter('apikey', 'a-strong-secret'))
TMVCRangeMediaMiddlewareRangeMediaHTTPFilterUse(RangeMediaHTTPFilter('/static/media', 'static/media'))
TMVCSwaggerMiddlewareSwaggerHTTPFilterUse(SwaggerHTTPFilter(AEngine, lSwaggerInfo, '/openapi.json'))
TMVCOpenAPI3MiddlewareOpenAPIHTTPFilterUse(OpenAPIHTTPFilter(AEngine, lOpenAPIInfo, '/openapi.json'))
TMVCRateLimitMiddlewareRateLimitHTTPFilterUse(RateLimitHTTPFilter(lRateLimitOptions))
TMVCActiveRecordMiddlewareActiveRecordHTTPFilterUse(ActiveRecordHTTPFilter('conn_def_name', 'FDConnectionDefs.ini'))
UseMemorySessionMiddlewareMemorySessionHTTPFilterUse(MemorySessionHTTPFilter(10, [scfHttpOnly, scfSecure]))
UseFileSessionMiddlewareFileSessionHTTPFilterUse(FileSessionHTTPFilter(10, 'sessions', [scfHttpOnly, scfSecure]))
UseDatabaseSessionMiddlewareDatabaseSessionHTTPFilterUse(DatabaseSessionHTTPFilter(10, [scfHttpOnly, scfSecure])), after ActiveRecordHTTPFilter

ActiveRecordHTTPFilter and DatabaseSessionHTTPFilter are not in MVCFramework.Filters but in MVCFramework.Filters.ActiveRecord, SwaggerHTTPFilter is in MVCFramework.Filters.Swagger and OpenAPIHTTPFilter in MVCFramework.Filters.OpenAPI. This way the base layer does not depend on FireDAC, on SwagDoc or on the OpenAPI emitter. If you use those filters, add the unit to your uses.

WaitForShutdownOrConsoleReturn, which in TMVCShutdownMiddleware was a class method, is now a procedure of MVCFramework.Filters. StaticFilesHTTPFilter also has an overload that takes a TMVCStaticFilesOptions, with the options of the classic middleware: charset, fallback for single page applications, MIME type customization, per-request rules.

The last five are new filters that controllers can use as well:

  • The session filters attach the session factory to every request, and Context.Session is used as always. DatabaseSessionHTTPFilter must be registered after ActiveRecordHTTPFilter.
  • ActiveRecordHTTPFilter takes the connection before the dispatch and releases it when ANext() returns. The additional connections apply to every instance of the filter: the middleware enabled them only for the first one in the process.
  • RateLimitHTTPFilter with TMVCRateLimitOptions has the same options and the same response as the middleware: key by IP, user, API key or custom, excluded path prefixes, prefix of the X-RateLimit-* headers, a callback when a request is rejected. The response is 429 with Retry-After and a JSON body. The simple form, RateLimitHTTPFilter(10, 60), is still there.

If your code still uses one of these middleware, the compiler tells you this:

[dcc32 Warning] W1000 Symbol 'TMVCStaticFilesMiddleware' is deprecated: 'Use the StaticFiles HTTP filter (MVCFramework.Filters): AEngine.Use(StaticFilesHTTPFilter(...))'

It is a warning, not an error. The code keeps compiling and working.


What the wizard generates

As a consequence, the wizard for new projects, the one from the RC7 post, generates filters instead of those middleware. For a controller project with static files, CORS, ETag, compression, trace, rate limit, ActiveRecord and sessions, EngineConfigU contains a single chain:

Filter chain generated by the wizard in EngineConfigU: RedirectHTTPFilter, FileServerBundle, TraceHTTPFilter, CORSHTTPFilter, ETagHTTPFilter, CompressionHTTPFilter, RateLimitHTTPFilter, ActiveRecordHTTPFilter and MemorySessionHTTPFilter, each registered with AEngine.Use

Copy the code
  // HTTPFilter chain (engine-wide). Order matters: first = outermost. The filters wrap the whole
  // request: the classic middleware, the routing and the action.
  AEngine.Use(RedirectHTTPFilter(['/'], '/web'));
  AEngine.Use(FileServerBundle('/static', lWwwPath));
  AEngine.Use(TraceHTTPFilter());
  AEngine.Use(CORSHTTPFilter('*'));
  AEngine.Use(ETagHTTPFilter());
  AEngine.Use(CompressionHTTPFilter(1024));
  AEngine.Use(RateLimitHTTPFilter(lRateLimitOptions));
  AEngine.Use(ActiveRecordHTTPFilter(
    dotEnv.Env('firedac.connection_definition_name', 'activerecorddb'),
    dotEnv.Env('firedac.connection_definitions_filename', TPath.Combine(AppPath, 'FDConnectionDefs.ini'))
  ));
  AEngine.Use(MemorySessionHTTPFilter(10, SessionCookieFlags(dotEnv.Env('SESSION_COOKIE_SECURE', True))));

The block is an example: the connection names depend on the generated project, and lRateLimitOptions is prepared just above with TMVCRateLimitOptions.Default.

The first one registered is the outermost. The order the wizard uses is RedirectHTTPFilter, FileServerBundle, AnalyticsHTTPFilter, TraceHTTPFilter, CORSHTTPFilter, ETagHTTPFilter, CompressionHTTPFilter, RateLimitHTTPFilter, the API documentation, ActiveRecordHTTPFilter and the session filters. Sessions and the database connection sit in the innermost position, so a request rejected with 429 or served as a static file does not open a connection.

For static files the wizard uses FileServerBundle instead of StaticFilesHTTPFilter. It serves files the same way and also answers requests that carry a Range header with 206 Partial Content, like RangeMediaHTTPFilter. A bundle is a package of filters that a single Use registers in the right order; this one has only the HTTP part.

ETagHTTPFilter comes before CompressionHTTPFilter because it computes the hash after ANext() has returned. If ETagHTTPFilter is the outer one, compression has already rewritten the body, and the ETag matches the bytes the client receives.

Relative to AddMiddleware, the registration order does not matter: the filters wrap the classic middleware anyway, even the ones that respond on their own, like static files or the redirect.

For OpenAPI and Swagger the wizard uses Use(SwaggerHTTPFilter(...)) for the document endpoint and Use(StaticFilesHTTPFilter(lSwaggerUIOptions)) for the Swagger UI under /swagger. The same goes for WebBroker projects and for Minimal API ones, which were already using the chain.

In the uses clause the wizard no longer writes MVCFramework.Middleware.Redirect, .StaticFiles, .Analytics, .Trace, .CORS, .ETag, .Compression, .Swagger, .RateLimit, .Session and .ActiveRecord. It adds MVCFramework.Filters and, when they are needed, MVCFramework.Filters.ActiveRecord, MVCFramework.Filters.Swagger and MVCFramework.Filters.OpenAPI, plus MVCFramework.MinimalAPI in Minimal API projects.

The wizard installed in the IDE generates from the templates inside its package. To see the new chain you need the RC9 package.


If you migrate a project

With 4.0 the middleware will be gone, so for the middleware that already have a filter the switch should be made before you upgrade. For the three most common it looks like this (add MVCFramework.Filters to your uses). StaticFilesHTTPFilter in this form is not identical to the middleware: the single page application fallback is off, more on that below:

Before and after: AddMiddleware with TMVCRedirectMiddleware, TMVCStaticFilesMiddleware and TMVCCORSMiddleware becomes Use with RedirectHTTPFilter, StaticFilesHTTPFilter and CORSHTTPFilter

Copy the code
// before
AEngine.AddMiddleware(TMVCRedirectMiddleware.Create(['/'], '/web'));
AEngine.AddMiddleware(TMVCStaticFilesMiddleware.Create('/static', lWwwPath));
AEngine.AddMiddleware(TMVCCORSMiddleware.Create);

// after
AEngine.Use(RedirectHTTPFilter(['/'], '/web'));
AEngine.Use(StaticFilesHTTPFilter('/static', lWwwPath));
AEngine.Use(CORSHTTPFilter('*'));

The default values of some filters do not match those of the middleware. For these I compared the source of the two, filter by filter.

CORS

TMVCCORSMiddlewareCORSHTTPFilter
Credentialsonoff
Allowed headersContent-Type, Accept, jwtusername, jwtpassword, authentication, authorizationContent-Type,Authorization
MethodsPOST,GET,OPTIONS,PUT,DELETE,PATCHGET,POST,PUT,DELETE,PATCH,OPTIONS
Max-age60 seconds1728000 seconds

If a client depends on the old values, you pass them as parameters:

CORSHTTPFilter with the parameters that reproduce the classic middleware values: credentials on, headers and methods from the old list, max-age 60

Copy the code
AEngine.Use(CORSHTTPFilter('*', True, '',
  'Content-Type, Accept, jwtusername, jwtpassword, authentication, authorization',
  'POST,GET,OPTIONS,PUT,DELETE,PATCH', 60));

The filter responds to the preflight before routing and adds the headers to error responses as well: a 404 carries Access-Control-Allow-Origin.

ETag

The filter writes the ETag quoted, as RFC 7232 requires, accepts the W/ prefix in If-None-Match and acts only on 2xx responses. The classic middleware writes the SHA-1 digest without quotes and compares it as is with If-None-Match. If the action has already set an ETag, the classic middleware leaves it, the filter replaces it with its own. In both cases only responses that have a ContentStream get the ETag: a string response does not.

Redirect

The filter responds with 302 (301 with rdkPermanent, the third parameter) and keeps the query string; with rdqDrop, the fourth parameter, it drops it: RedirectHTTPFilter(['/old'], '/new', rdkPermanent, rdqDrop). It compares the path case-insensitively; the middleware compares the exact text.

Analytics

The CSV file has the same columns. The fifth one, which in the middleware contains controller and action, in the filter contains the PathInfo: an HTTP filter has no controller to name.

Swagger

SwaggerHTTPFilter lives in MVCFramework.Filters.Swagger and builds the document with the same code as TMVCSwaggerMiddleware, now deprecated; OpenAPIHTTPFilter lives in MVCFramework.Filters.OpenAPI. The JWT authentication is looked up when the document is generated, once the request has been received, so the registration order does not matter. The lookup only finds the classic middleware, TMVCJWTAuthenticationMiddleware, though: with JWTAuthenticationBundle the Bearer scheme appears only if you ask for it with [sauBearer], and the login route does not end up in the document.

The two authentication schemes of the document, Basic and Bearer, are two Booleans in the middleware, the fifth and the tenth parameter. In the filter they are a set in fifth position, [sauBasic, sauBearer], so the filter has one parameter fewer: if you copy the middleware arguments one to one, the compiler stops at the fifth. The wizard passes [sauBearer] when the project uses JWT in the header, otherwise [].

Sessions

The two Booleans of the session middleware, HttpOnly and Secure, become a set in the filters, TMVCSessionCookieFlags, which defaults to [scfHttpOnly]. So changing the name of the function is not enough:

UseFileSessionMiddleware(10, True, ‘sessions’, True) becomes FileSessionHTTPFilter(10, ‘sessions’, [scfHttpOnly, scfSecure]): the two Booleans become a set of flags

Copy the code
// before
AEngine.AddMiddleware(UseFileSessionMiddleware(10, True, 'sessions', True));

// after
AEngine.Use(FileSessionHTTPFilter(10, 'sessions', [scfHttpOnly, scfSecure]));

If you copy the parameters one to one the compiler complains, because where there was a Boolean there is now a set. To build the set from a Boolean there is SessionCookieFlags: it always has HttpOnly, and Secure only if the parameter is true. It is what the code generated by the wizard uses.

For any session factory there is SessionHTTPFilter(factory), and SessionEndpointFilter(factory) for Minimal API groups: the filter takes ownership of it. MemorySessionHTTPFilter, FileSessionHTTPFilter and DatabaseSessionHTTPFilter are built on top of it, and the last one lives in MVCFramework.Filters.ActiveRecord.

Booleans and enums

In the filter signatures I avoided Booleans when the True doesn’t explain itself, the boolean trap. In UseFileSessionMiddleware(10, True, 'sessions', True) the reader can’t tell which True is HttpOnly and which is Secure, and has to open the declaration. The session filters take the TMVCSessionCookieFlags set instead, which is self-explanatory: [scfHttpOnly, scfSecure]. The same goes for the other filters:

  • RedirectHTTPFilter tells 302 and 301 apart with TMVCRedirectKind (rdkTemporary, rdkPermanent) and keeps or drops the query string with TMVCRedirectQuery (rdqPreserve, rdqDrop);
  • TraceHTTPFilter takes the TMVCTraceFlags set (tfLogAuthorization, tfLogNonTextBody);
  • SwaggerHTTPFilter takes the TMVCSwaggerAuthentications set (sauBasic, sauBearer);
  • the options of StaticFilesHTTPFilter have Mode (sfmFiles, sfmSPA) and Flags (sffCaseSensitivePrefix).

Two parameters are still Booleans. AAllowsCredentials of CORSHTTPFilter mirrors the parameter with the same name in the CORS middleware, so the call looks the same in both styles. SessionCookieFlags(ASecure) turns a value read at run time from the .env file into flags, as the code generated by the wizard does.

Rate limit

The simple form, RateLimitHTTPFilter(10, 60), is still there. For the options you prepare a TMVCRateLimitOptions, as the code generated by the wizard does:

RateLimitHTTPFilter with TMVCRateLimitOptions: 10 requests in 60 seconds, /health path excluded, OnExceeded callback that writes to the log

Copy the code
lRateLimitOptions := TMVCRateLimitOptions.Default;
lRateLimitOptions.MaxRequests := 10;
lRateLimitOptions.WindowSeconds := 60;
lRateLimitOptions.ExcludedPaths := ['/health'];
lRateLimitOptions.OnExceeded :=
  procedure(const AContext: TWebContext; const AKey: string;
    const ALimit: Integer; const AWindowSeconds: Integer)
  begin
    LogW(Format('Rate limit exceeded for key: %s (Limit: %d requests per %d seconds)',
      [AKey, ALimit, AWindowSeconds]));
  end;
AEngine.Use(RateLimitHTTPFilter(lRateLimitOptions));

StaticFiles

The simple form, StaticFilesHTTPFilter('/static', lWwwPath), and the one with options, StaticFilesHTTPFilter(TMVCStaticFilesOptions), are the same implementation. The main difference from TMVCStaticFilesMiddleware is the single page application fallback: in the middleware it was on by default, in the filter it is off. In the simple form you turn it on with sfmSPA:

StaticFilesHTTPFilter on / with sfmSPA, for a single page application with the API next to it

Copy the code
AEngine.Use(StaticFilesHTTPFilter('/', 'www/app', sfmSPA));

With sfmSPA the filter lets the request through to the router, and responds with the index.html of the nearest existing folder only to a GET or HEAD for which the application has no route at all. The API routes are never hidden, so the SPA can sit at / with the API next to it. With the options you set Mode := sfmSPA; in TMVCStaticFilesOptions.Default it is sfmFiles. The third parameter of the simple form is the mode (sfmFiles or sfmSPA), the index document, index.html by default, is the fourth.

Two limits. You need AllowUnhandledAction = false, which is the default. And the router keeps writing “ROUTE NOT FOUND” to the log for every client-side route.

The rest is as in the middleware: the prefix is case-insensitive (with sffCaseSensitivePrefix in Flags it is case-sensitive), with or without the trailing /, files are served with their MIME type and with Last-Modified (and 304 on If-Modified-Since), a folder without the trailing / responds with 301 and then serves its index.html. Two differences remain. The middleware wrote a log line for every file served, with method, status, path, IP and duration, and the filters don’t. The filter serves .webp, .woff, .woff2 and .ttf with the right type, which the middleware didn’t know. The other options of the middleware, charset, custom MIME types and per-request rules, are available with TMVCStaticFilesOptions.

If you also need Range requests, for audio and video, there is FileServerBundle, the one the wizard uses for /static. The form is the same, with the modes fsmFiles and fsmSPA: FileServerBundle('/', 'www/app', fsmSPA).

Compression

The 1024-byte threshold, the compression level and the choice of encoding (the first of gzip and deflate in the order of the Accept-Encoding header) are those of the middleware. One thing changes: the filter does not compress a response that already has a Content-Encoding. RangeMediaHTTPFilter sets Content-Encoding: identity on partial responses, and compressing them would break Content-Range.

The other filters

TraceHTTPFilter behaves like the middleware. Every log line carries the correlation id [rid:...], and the same id comes back in the X-Request-ID response header: it is the caller’s if there is one, otherwise it generates a six-digit hexadecimal one. Authorization appears with the scheme and three asterisks, Bearer ***, and the response headers Authorization, Proxy-Authorization, Cookie and Set-Cookie are masked. The body is logged up to 1024 bytes. The signature has a parameter the middleware does not have, the third one: TraceHTTPFilter(AMaxBodySize, ALogTag, AFlags, ACorrelationHeaderName). AFlags is a set, empty by default: with tfLogAuthorization the request Authorization is written in clear text, with tfLogNonTextBody bodies that are not text are logged too. The header name, X-Request-ID by default, was the third parameter in the middleware and is now the fourth: if you passed it, the compiler tells you.

SecurityHeadersHTTPFilter writes the same two headers as the middleware, X-XSS-Protection: 0 and X-Content-Type-Options: nosniff, and has no parameters. ShutdownHTTPFilter responds only to POST requests on /api/shutdown, as before. RangeMediaHTTPFilter and OpenAPIHTTPFilter have the same values as the middleware, and OpenAPIHTTPFilter serves the document on /openapi.json. ActiveRecordHTTPFilter reads FDConnectionDefs.ini like the middleware, but it is written natively and releases the connection in a finally around ANext().

I compared the default values by reading the source of the middleware and of the filter. If you find a difference I haven’t listed, open an issue.


Endpoint filters

The second responsibility of the classic middleware, controlling how actions are executed, goes to the endpoint filter. An endpoint filter is this function:

Signature of an endpoint filter: a function with AContext of type TWebContext and ANext of type TMVCEndpointFilterNext that returns an IMVCResponse

Copy the code
function(const AContext: TWebContext; const ANext: TMVCEndpointFilterNext): IMVCResponse

It runs after routing, when the framework already knows which action or which Minimal API route will respond. As in the HTTP filter, the code before ANext() runs before the action and the code after it runs when the action has finished. Unlike the HTTP filter it is a function, and it returns an IMVCResponse.

When it runs

To see the order I set up a server with an HTTP filter, a classic middleware with all four methods, an endpoint filter registered on the engine, a controller and a Minimal API route, and had each of them write a line to the console. This is a GET to the controller action:

HTTP filter: before ANext()
  MW  OnBeforeRouting
  MW  OnBeforeControllerAction(PipelineOrder.TOrderController, Hello)
    EF  engine endpoint filter: before ANext(), ControllerQualifiedClassName="PipelineOrder.TOrderController", ActionName="Hello", Params[id]="42"
      ACTION TOrderController.Hello(id=42)
    EF  engine endpoint filter: after ANext(), ANext() returned nil, Response.StatusCode=200
  MW  OnAfterControllerAction(PipelineOrder.TOrderController, Hello, AHandled=False)
  MW  OnAfterRouting(AHandled=False)
HTTP filter: after ANext(), Response.StatusCode=200

And this is a GET to the Minimal API route, which also has a filter on its group, /min:

HTTP filter: before ANext()
  MW  OnBeforeRouting
    EF  engine endpoint filter: before ANext(), ControllerQualifiedClassName="", ActionName="GET /min/hello/($id)", Params[id]="42"
     GF  group endpoint filter (/min): before ANext()
      HANDLER Minimal API GET /min/hello/($id) (id=42)
     GF  group endpoint filter (/min): after ANext()
    EF  engine endpoint filter: after ANext(), ANext() returned IMVCResponse status 200, Response.StatusCode=200
  MW  OnAfterRouting(AHandled=True)
HTTP filter: after ANext(), Response.StatusCode=200

The output shows that:

  • endpoint filters run after every OnBeforeControllerAction of the classic middleware, and their part after ANext() finishes before any OnAfterControllerAction, whatever the registration order;
  • a Minimal API route does not go through OnBeforeControllerAction and OnAfterControllerAction, because the Minimal API runs inside the OnBeforeRouting of a middleware of its own, while the endpoint filter runs in both cases;
  • ANext() returns nil for a controller action, which has already written the response, and the handler’s IMVCResponse for a Minimal API route, where the response is written afterwards.

A request that never reaches a route, such as a 404 or a static file served by an HTTP filter, does not go through the endpoint filters. If you keep classic middleware in a Minimal API project, note that the ones added after the first call to Root or Prefix don’t even get OnBeforeRouting for the Minimal API routes.

Stopping the request, and the code after the action

To stop the request you return a response without calling ANext(). This filter responds with 400 when a header is missing, and the action does not run:

Endpoint filter that responds with 400 through BadRequest when a header is missing, and calls ANext only when the header is there

Copy the code
function RequireHeaderEndpointFilter(const AHeaderName: string): TMVCEndpointFilter;
begin
  Result :=
    function(const AContext: TWebContext; const ANext: TMVCEndpointFilterNext): IMVCResponse
    begin
      if AContext.Request.Headers[AHeaderName].Trim.IsEmpty then
        Exit(BadRequest('Missing header ' + AHeaderName)); // no ANext(): the action does not run
      Result := ANext();
    end;
end;

On a controller, the response returned by the filter always goes out as JSON, whatever the content type of the controller. OnAfterControllerAction still runs on the classic middleware, with AHandled = True.

The code after ANext() does the job of OnAfterControllerAction. This filter logs which action ran and how long it took:

Endpoint filter that times the action with TStopwatch and, in a finally block, logs controller, action and milliseconds

Copy the code
function ActionTimingEndpointFilter: TMVCEndpointFilter;
begin
  Result :=
    function(const AContext: TWebContext; const ANext: TMVCEndpointFilterNext): IMVCResponse
    var
      lWatch: TStopwatch;
    begin
      lWatch := TStopwatch.StartNew;
      try
        Result := ANext();
      finally
        // runs even when the action raises
        // ControllerQualifiedClassName is '' for a Minimal API route, ActionName is then 'GET /pattern'
        LogI(Format('%s %s took %d ms',
          [AContext.ControllerQualifiedClassName, AContext.ActionName, lWatch.ElapsedMilliseconds]));
      end;
    end;
end;

The finally is needed because an exception raised by the action comes back through ANext(): the endpoint filter sees it, and with try..finally its code runs anyway, while with try..except it can inspect the exception. In that case OnAfterControllerAction is skipped. It is different in an HTTP filter: there the engine has already handled the exception and responded with 500, and the code after ANext() runs without any need for a finally.

Where you register it

WhereHowFor which requests
EngineAEngine.Use(filter)every controller action and every Minimal API route
Minimal API grouplGroup := lGroup.Use(filter)the routes mapped afterwards on the group and on its nested groups
One routelGroup.MapGet(...).Use(filter)that route only

Two endpoint filters registered on the engine with AEngine.Use, and one on the Minimal API group /api/v1, keeping the group returned by Use

Copy the code
// every controller action and every Minimal API route
AEngine
  .Use(ActionTimingEndpointFilter())                // the first registered is the outermost: it also times the check
  .Use(RequireHeaderEndpointFilter('X-Tenant-ID'));

// or only the routes of /api/v1 and of the groups nested in it;
// a group is an immutable record: keep what Use returns, and call Use before MapXxx
lApi := AEngine.Prefix('/api/v1').Use(RequireHeaderEndpointFilter('X-Tenant-ID'));

The first one registered is the outermost. A Minimal API route goes through the engine filters first, then through the group filters, starting from the outermost group, then through the route’s own filters. All HTTP filters sit outside all endpoint filters.

The group is an immutable record, and that makes two mistakes easy. lGroup.Use(F); without assigning the result does nothing, because Use returns a new group. And each route copies the group’s filters when you map it, so a Use after MapGet does not reach the routes already mapped.

There is no Use for a single controller, and no attribute either. A filter meant for one controller checks AContext.ControllerQualifiedClassName and, for all the others, just calls ANext().

What it sees

After routing, the filter knows which route the request matched. In the test above, with /ctrl/hello/42 and /min/hello/42:

Controller actionMinimal API route
AContext.ControllerQualifiedClassNamePipelineOrder.TOrderControllerempty
AContext.ActionNameHelloGET /min/hello/($id)
AContext.Request.Params['id']4242

AContext.LoggedUser is filled in if an authentication filter earlier in the chain has recognized the user. The filter does not see the action’s attributes or the controller instance.

From the two hooks to the endpoint filter

A middleware that uses OnBeforeControllerAction and OnAfterControllerAction becomes an endpoint filter like this: the first one is the code before ANext(), the second one the code after it, and AHandled := True is a response returned without calling ANext(). The filter also runs for Minimal API routes, and with a finally the code after ANext() runs even when the action raises an exception.

Ready-made endpoint filters

FilterWhat it does
AuthorizeEndpointFilter()401 if no authentication filter has recognized the user
RequireRoleEndpointFilter('admin')401 without a user, 403 if the user has none of the roles
BasicAuthEndpointFilter(...)Basic authentication: 401 with WWW-Authenticate, 403 if the user is not authorized
CORSEndpointFilter(...)CORS headers on route responses
CSRFEndpointFilter(...)CSRF check on requests that match a route
SessionEndpointFilter, MemorySessionEndpointFilter, FileSessionEndpointFilter, DatabaseSessionEndpointFiltersessions
ActiveRecordEndpointFilter('conn_def_name')ActiveRecord connection around the action

They work for controllers, with AEngine.Use, and for Minimal API groups. For a whole API, though, CORS and sessions belong in HTTP filters. CORSEndpointFilter answers the preflight only on a route registered for OPTIONS, while CORSHTTPFilter answers every preflight. And a session registered as an endpoint filter arrives after the HTTP filters and after every OnBeforeControllerAction, too late for a login that uses it.


Bundles

Some mechanisms need both kinds of filter. JWT is the typical case: the login does not need a route, so it is an HTTP filter, while the token check has to know which action is about to run, so it is an endpoint filter. Registering only one half, or the two halves with different parameters, would be a configuration mistake that the compiler cannot see. That is why the two halves come together in a bundle:

The IMVCFilterBundle interface declared in MVCFramework.pas: two functions, HTTPFilters and EndpointFilters

Copy the code
IMVCFilterBundle = interface
  ['{35D2589D-F40A-426D-925F-87A7722A88C8}']
  function HTTPFilters: TArray<TMVCHTTPFilter>;
  function EndpointFilters: TArray<TMVCEndpointFilter>;
end;

AEngine.Use(bundle) puts the bundle’s HTTP filters into the HTTP filter chain and its endpoint filters into the endpoint filter chain, at the point where you call it, keeping their order. FileServerBundle, the one for static files, is a bundle with only the HTTP part.

Authentication bundles

BundleHTTP partEndpoint partMiddleware it replaces
JWTAuthenticationBundlelogin; blacklist and refresh token, if you configure themtoken check in Authorization: BearerTMVCJWTAuthenticationMiddleware, TMVCJWTBlackListMiddleware, TMVCJWTRefreshTokenMiddleware
JWTCookieAuthenticationBundlelogin and logout, with a check on the Origin of the login request (LoginAllowedOrigins)token check in the cookieTMVCJWTCookieAuthenticationMiddleware
BasicAuthenticationBundlenoneBasicAuthEndpointFilterTMVCBasicAuthenticationMiddleware
CustomAuthenticationBundlelogin and logout on /system/users/loggedsession checkTMVCCustomAuthenticationMiddleware, TMVCRoleBasedAuthMiddleware (with TRoleBasedAuthHandler)
OIDCAuthenticationBundlelogin, callback and logoutvalid session, otherwise 302 to the loginTMVCOIDCAuthenticationMiddleware

The first four are in MVCFramework.Filters.Authentication, OIDCAuthenticationBundle is in MVCFramework.Filters.OIDC. CSRF has two filters instead of a bundle: CSRFHTTPFilter checks before routing, as the middleware does, and CSRFEndpointFilter after it.

The bundle and the deprecated middleware run the same code: the logic lives in the filter units, and the middleware is now a thin wrapper over it, with the 3.4 API. With the same IMVCAuthenticationHandler, the bundle checks and responds the way the middleware does. Like the seventeen, the authentication middleware will keep working up to, but not including, 4.0, and the compiler warning names the bundle to use: for TMVCJWTAuthenticationMiddleware it is AEngine.Use(JWTAuthenticationBundle(...)).

The short form of the JWT bundle:

JWTAuthenticationBundle registered with AEngine.Use: authentication handler, anonymous method that sets the token claims, and secret

Copy the code
AEngine.Use(JWTAuthenticationBundle(TMyAuthHandler.Create,
  procedure(const AJWT: TJWT)
  begin
    AJWT.Claims.Issuer := 'my-server';
    AJWT.Claims.ExpirationTime := IncHour(Now, 1);
    AJWT.Claims.NotBefore := IncMinute(Now, -5);
    AJWT.Claims.IssuedAt := Now;
  end,
  lSecret));

I tried it on Indy Direct. POST /login with the jwtusername and jwtpassword headers responds with 200 and {"token":"eyJ..."}, or with 401 if the password is wrong. From then on every action and every Minimal API route asks for the token, except the actions that the handler makes public in OnRequest: on Minimal API routes OnRequest is not called, so the token is always required. Without a token a controller responds with 401 and {"classname":"","message":"Authorization Required"}, while a Minimal API route responds with 401 and an application/problem+json body.

The options let you turn on refresh tokens: you just assign a store.

JWTAuthenticationBundle with TMVCJWTAuthenticationOptions: handler, secret, login URL, token lifetime and refresh token store

Copy the code
lOptions := TMVCJWTAuthenticationOptions.Default;
lOptions.Handler := TMyAuthHandler.Create;
lOptions.Secret := lSecret;
lOptions.LoginURL := '/auth/login';
lOptions.RefreshToken.Issuer := 'my-server';
lOptions.RefreshToken.AccessTokenTTLSeconds := 15 * 60;
// a store turns the refresh token on; one store for the whole process
lOptions.RefreshTokenStore := gRefreshStore;
AEngine.Use(JWTAuthenticationBundle(lOptions));

There is one store for the whole process, created in initialization with TMVCInMemoryRefreshTokenStore.Create: under WebBroker, ISAPI and Apache each web module has its own engine. The login, a POST /auth/login with {"username":...,"password":...}, responds with access_token, refresh_token, token_type and expires_in. POST /auth/refresh returns a new pair. If the same refresh token arrives a second time, the response is 401 with {"error": "Refresh token reuse detected; session revoked"}.

CustomAuthenticationBundle must be registered after a session HTTP filter, for example MemorySessionHTTPFilter: the classic session middleware runs after all the HTTP filters, too late for the login.

A bundle on a Minimal API group

On a group, Use puts the HTTP part on the engine and the endpoint part on the group:

Minimal API group /api/v1 with a public route and a nested /admin group with JWTAuthenticationBundle and RequireRoleEndpointFilter

Copy the code
lApi := AEngine.Prefix('/api/v1');
lApi.MapGet('/products',
  function: IMVCResponse
  begin
    Result := Ok('the product list'); // no token needed here
  end);

// login on the engine (it answers before routing), token and role checked on /api/v1/admin only
lAdmin := lApi.Prefix('/admin')
  .Use(JWTAuthenticationBundle(TMyAuthHandler.Create, lClaimsSetup, lSecret, '/api/v1/admin/login'))
  .Use(RequireRoleEndpointFilter('admin'));
lAdmin.MapGet<TWebContext>('/stats',
  function(AContext: TWebContext): IMVCResponse
  begin
    Result := Ok('stats for ' + AContext.LoggedUser.UserName);
  end);

The login on /api/v1/admin/login responds before routing, even though there is no route at that address. /api/v1/admin/stats responds with 401 without a token, 403 with the token of a user who lacks the admin role, and 200 with an administrator’s token. /api/v1/products, outside /admin, asks for nothing.

Here too, keep the result of Use: if you discard it, the login stays on the engine and the routes of the group do not check the token.

A bundle of your own

TMVCFilterBundle implements the interface and holds the two lists. It has no virtual methods to override: a bundle of your own is a function that creates one with your filters, which is what the framework does for FileServerBundle and for the authentication bundles. This one gives every response an id, 404s and static files included, and writes an audit line with the same id only for the requests that reach an action:

Hand-written bundle: RequestIdHTTPFilter puts an id on every response, AuditEndpointFilter writes a log line for the actions, RequestAuditBundle combines them with TMVCFilterBundle.Create

Copy the code
const
  REQUEST_ID = 'request_id';

// HTTP part: every response gets an id, 404s and static files included
function RequestIdHTTPFilter(const AHeaderName: string): TMVCHTTPFilter;
begin
  Result :=
    procedure(const AContext: TWebContext; const ANext: TMVCHTTPFilterNext)
    var
      lId: string;
    begin
      lId := AContext.Request.Headers[AHeaderName];
      if lId.IsEmpty then
        lId := TGUID.NewGuid.ToString;
      AContext.Data[REQUEST_ID] := lId;
      AContext.Response.SetCustomHeader(AHeaderName, lId);
      ANext();
    end;
end;

// endpoint part: an audit line, with the same id, for the requests that reach an action
function AuditEndpointFilter: TMVCEndpointFilter;
begin
  Result :=
    function(const AContext: TWebContext; const ANext: TMVCEndpointFilterNext): IMVCResponse
    begin
      LogI(Format('[%s] %s %s by "%s"', [AContext.Data[REQUEST_ID],
        AContext.ControllerQualifiedClassName, AContext.ActionName, AContext.LoggedUser.UserName]));
      Result := ANext();
    end;
end;

function RequestAuditBundle(const AHeaderName: string = 'X-Request-ID'): IMVCFilterBundle;
begin
  Result := TMVCFilterBundle.Create([RequestIdHTTPFilter(AHeaderName)], [AuditEndpointFilter()]);
end;

You register it with AEngine.Use(RequestAuditBundle()).

Use checks the configuration at startup and raises EMVCConfigException if you register the same bundle instance twice, if you register it on the engine and on a group, or if you put a bundle without an endpoint part on a group, such as FileServerBundle. The check looks at the instance: two calls to JWTAuthenticationBundle(...) create two bundles, and therefore two logins and two checks.


Frequently asked questions

Why does DelphiMVCFramework add HTTP filters alongside middleware? The classic middleware had two responsibilities: influencing routing and controlling how actions are executed. The HTTP filter splits off the first one using the next mechanism, the same one used by Express, Koa, ASP.NET Core, Laravel, Starlette, FastAPI, Gin and axum: a procedure that receives the context and ANext, and decides whether and when to pass the request on to whatever comes after. The second responsibility goes to the endpoint filter, which runs after routing.

Which DelphiMVCFramework middleware are deprecated? Seventeen middleware, fourteen classes and three creation functions: TMVCRedirectMiddleware, TMVCStaticFilesMiddleware, TMVCAnalyticsMiddleware, TMVCTraceMiddleware, TMVCCompressionMiddleware, TMVCETagMiddleware, TMVCCORSMiddleware, TMVCSecurityHeadersMiddleware, TMVCShutdownMiddleware, TMVCRangeMediaMiddleware, TMVCSwaggerMiddleware, TMVCOpenAPI3Middleware, TMVCRateLimitMiddleware, TMVCActiveRecordMiddleware and the functions UseMemorySessionMiddleware, UseFileSessionMiddleware, UseDatabaseSessionMiddleware. Each has an HTTP filter in MVCFramework.Filters (RedirectHTTPFilter, StaticFilesHTTPFilter, AnalyticsHTTPFilter, TraceHTTPFilter, CompressionHTTPFilter, ETagHTTPFilter, CORSHTTPFilter, SecurityHeadersHTTPFilter, ShutdownHTTPFilter, RangeMediaHTTPFilter, SwaggerHTTPFilter, OpenAPIHTTPFilter, RateLimitHTTPFilter, ActiveRecordHTTPFilter, MemorySessionHTTPFilter, FileSessionHTTPFilter, DatabaseSessionHTTPFilter), registered with AEngine.Use. ActiveRecordHTTPFilter and DatabaseSessionHTTPFilter are in MVCFramework.Filters.ActiveRecord, SwaggerHTTPFilter in MVCFramework.Filters.Swagger and OpenAPIHTTPFilter in MVCFramework.Filters.OpenAPI: if you use them, add the unit to your uses. The authentication middleware are deprecated too (JWT in header and in cookie, blacklist, refresh token, Basic, custom authentication, RoleBased, OIDC, CSRF): they have their own filters, partly HTTP filters and partly endpoint filters.

Does my existing server stop working? No, not in the 3.5 line. Nothing has been removed. The compiler shows the W1000 warning for every deprecated middleware you use, and the code compiles and runs as before.

What happens to the middleware in 4.0? They will be removed altogether. Up to, but not including, 4.0 they keep working, with a compiler warning. All the deprecated middleware already have their filter and can be replaced today: the seventeen in this article with an HTTP filter, the authentication ones with a bundle (JWTAuthenticationBundle and the others).

Can I use sessions, ActiveRecord and rate limit as filters in controllers? Yes. MemorySessionHTTPFilter, FileSessionHTTPFilter, DatabaseSessionHTTPFilter, ActiveRecordHTTPFilter and RateLimitHTTPFilter with TMVCRateLimitOptions are HTTP filters, so they apply to controllers. DatabaseSessionHTTPFilter must be registered after ActiveRecordHTTPFilter. The wizard generates them instead of the classic middleware.

What about the JWT, Basic, OIDC and CSRF middleware? They are deprecated and have their own bundles: JWTAuthenticationBundle, JWTCookieAuthenticationBundle, BasicAuthenticationBundle, CustomAuthenticationBundle and OIDCAuthenticationBundle. Login, logout, callback and blacklist are the HTTP part of the bundle, the request check is the endpoint part, which runs after routing because controller authorization is based on the name of the controller and of the action. CSRF has two filters, CSRFHTTPFilter and CSRFEndpointFilter. The middleware keep working up to, but not including, 4.0.

What is an endpoint filter and when does it run? It is a function that receives AContext and ANext and returns an IMVCResponse. It runs after routing, both for controller actions and for Minimal API routes (on a controller, after every OnBeforeControllerAction of the classic middleware), and it knows the name of the controller, the name of the action and the route parameters. You register it with AEngine.Use for the whole server, or on a group or a single route of the Minimal API.

What is a filter bundle? An IMVCFilterBundle is a package of HTTP filters and endpoint filters that a single Use registers in the right order. The authentication bundles put the login in the HTTP part and the check in the endpoint part; FileServerBundle has only the HTTP part. On a Minimal API group the HTTP part goes on the engine and the endpoint part on the group. A bundle of your own is a function that returns TMVCFilterBundle.Create with the two lists of filters.

In what order do I register filters and middleware? Relative to AddMiddleware the order does not matter: the filters wrap the classic middleware anyway. Among the filters the first one registered is the outermost, ETagHTTPFilter goes before CompressionHTTPFilter, and ActiveRecordHTTPFilter and the session filters sit in the innermost position.

What changes in the CORS default values when you switch to CORSHTTPFilter? The filter starts with credentials off, the Content-Type,Authorization headers, the methods GET,POST,PUT,DELETE,PATCH,OPTIONS and a max-age of 1728000 seconds. The classic middleware started with credentials on, a longer list of headers and the same methods in a different order. If you depend on the old values, you pass them as parameters to CORSHTTPFilter.

Besides CORSHTTPFilter, what changes in the default values of the filters compared to the middleware? The single page application fallback of StaticFilesHTTPFilter is off by default, while in the middleware it was on: you turn it on with StaticFilesHTTPFilter('/', folder, sfmSPA) or with Mode := sfmSPA in the options of TMVCStaticFilesOptions, and the router decides, so the API routes are not hidden and the SPA can sit on / as well. The filter does not write the per-file log line that the middleware wrote for every file served, and CompressionHTTPFilter does not compress a response that already has a Content-Encoding. TraceHTTPFilter, SecurityHeadersHTTPFilter, ShutdownHTTPFilter, OpenAPIHTTPFilter, RangeMediaHTTPFilter and ActiveRecordHTTPFilter have the same default values as the middleware.


Resources

– Daniele Teti

Key facts
  • Topic: the difference between classic middleware (IMVCMiddleware, AddMiddleware) and HTTP filters (TMVCHTTPFilter, registered with AEngine.Use) in DelphiMVCFramework, the REST and web framework for Delphi, and how to migrate. Release line 3.5.0-silicon; it will be in RC9 (3.5.0-silicon-rc9). The work described is not yet in a release. The article covers HTTP filters (before routing), endpoint filters (after routing) and the bundles that register them together.
  • It is not a breaking change: in 3.5.0-silicon filters are an additional feature and existing servers keep working the same way, with a compiler warning (W1000) for every deprecated middleware. The breaking change is planned for 4.0, where the middleware will be removed altogether. The transition is gradual because DelphiMVCFramework is used in critical environments (hospitals, banks, factories, video games, ERPs).
  • Why: the classic middleware had two responsibilities, influencing routing (OnBeforeRouting, OnAfterRouting) and controlling how actions are executed (OnBeforeControllerAction, OnAfterControllerAction). The HTTP filter splits off the first one using the next mechanism, also used by Express, Koa, ASP.NET Core, Laravel, Starlette, FastAPI, Gin and axum: a procedure (AContext, ANext) that runs before routing and wraps the whole dispatch; it works for controllers and Minimal API. OnBeforeRouting corresponds to the code before ANext(); OnAfterRouting, which fires at the very end, to the code after ANext(), which runs even when the action raises an exception (the engine responds with 500 inside ANext()). The second responsibility goes to the endpoint filter.
  • HTTP filters take the place of middleware wherever an equivalent exists. Seventeen middleware are marked deprecated (warning W1000, not an error), fourteen classes and three functions: TMVCRedirectMiddleware, TMVCStaticFilesMiddleware, TMVCAnalyticsMiddleware, TMVCTraceMiddleware, TMVCCompressionMiddleware, TMVCETagMiddleware, TMVCCORSMiddleware, TMVCSecurityHeadersMiddleware, TMVCShutdownMiddleware, TMVCRangeMediaMiddleware, TMVCSwaggerMiddleware, TMVCOpenAPI3Middleware, TMVCRateLimitMiddleware, TMVCActiveRecordMiddleware, UseMemorySessionMiddleware, UseFileSessionMiddleware, UseDatabaseSessionMiddleware. Filters: RedirectHTTPFilter, StaticFilesHTTPFilter, AnalyticsHTTPFilter, TraceHTTPFilter, CompressionHTTPFilter, ETagHTTPFilter, CORSHTTPFilter, SecurityHeadersHTTPFilter, ShutdownHTTPFilter, RangeMediaHTTPFilter, SwaggerHTTPFilter, OpenAPIHTTPFilter, RateLimitHTTPFilter (also with TMVCRateLimitOptions), ActiveRecordHTTPFilter, MemorySessionHTTPFilter, FileSessionHTTPFilter, DatabaseSessionHTTPFilter (unit MVCFramework.Filters, except ActiveRecordHTTPFilter and DatabaseSessionHTTPFilter in MVCFramework.Filters.ActiveRecord, SwaggerHTTPFilter in MVCFramework.Filters.Swagger and OpenAPIHTTPFilter in MVCFramework.Filters.OpenAPI, to be added to the uses clause). The name tells the kind: it ends in HTTPFilter, in EndpointFilter or in Bundle. A single method of TMVCEngine, AEngine.Use, registers HTTP filters, endpoint filters and bundles (IMVCFilterBundle, a package of filters put in the right order); a filter function with no parameters needs its parentheses inside Use, for example ETagHTTPFilter(). Nothing has been removed. As a consequence, the wizard for new projects generates the filters instead of those middleware, and for static files it uses FileServerBundle, which serves files like StaticFilesHTTPFilter and also answers Range requests with 206.
  • The authentication middleware have their filters too and are deprecated: JWT (header and cookie), blacklist, refresh token, Basic, custom authentication, RoleBased, OIDC, CSRF. Login, logout, callback and blacklist are HTTP filters; the request check is an endpoint filter (EndpointFilter), which runs after routing because controller authorization is based on the controller and action names. The two halves of each mechanism come in a bundle registered with a single Use: JWTAuthenticationBundle, JWTCookieAuthenticationBundle, BasicAuthenticationBundle, CustomAuthenticationBundle (unit MVCFramework.Filters.Authentication) and OIDCAuthenticationBundle (MVCFramework.Filters.OIDC). All deprecated middleware keep working up to, but not including, 4.0; in 4.0 they will be removed altogether.
  • Endpoint filters (TMVCEndpointFilter): a function (AContext, ANext) that returns an IMVCResponse. Order verified on Indy Direct: HTTP filters, OnBeforeRouting, routing, all the OnBeforeControllerAction, endpoint filters, action, all the OnAfterControllerAction, OnAfterRouting, HTTP filters. They apply to controller actions and to Minimal API routes (which do not go through OnBeforeControllerAction and OnAfterControllerAction). ANext() returns nil for a controller and the handler's IMVCResponse for a route. They are registered with AEngine.Use (the whole server), on a Minimal API group (lGroup := lGroup.Use(...), the group is an immutable record) or on a route; there is no Use for a single controller and no attribute. They see ControllerQualifiedClassName, ActionName and the route parameters. To stop the request you return a response without calling ANext(); the action's exception comes back through ANext() (OnAfterControllerAction is skipped in that case). Ready-made filters: AuthorizeEndpointFilter, RequireRoleEndpointFilter, BasicAuthEndpointFilter, CORSEndpointFilter, CSRFEndpointFilter, SessionEndpointFilter, MemorySessionEndpointFilter, FileSessionEndpointFilter, DatabaseSessionEndpointFilter, ActiveRecordEndpointFilter.
  • Bundles (IMVCFilterBundle, TMVCFilterBundle in MVCFramework): a package with a list of HTTP filters and a list of endpoint filters, registered by a single Use at the point of the call; on a Minimal API group the HTTP part goes on the engine and the endpoint part on the group. TMVCFilterBundle has no virtual methods: a custom bundle is a function that returns TMVCFilterBundle.Create([...], [...]). Use raises EMVCConfigException when the same instance is registered twice or on both the engine and a group, and for a bundle without an endpoint part on a group. JWTAuthenticationBundle: login POST /login with jwtusername/jwtpassword that responds {"token": ...}; with RefreshTokenStore in the options the login responds with access_token and refresh_token, and reusing a refresh token gives 401. CustomAuthenticationBundle must be registered after a session HTTP filter.
  • Order: the first registered filter is the outermost and the filters wrap the classic middleware whatever the order relative to AddMiddleware; ETagHTTPFilter before CompressionHTTPFilter; ActiveRecordHTTPFilter and sessions in the innermost position, so a rejected request (429) or one served as a static file does not open a connection.
  • Differences for those who migrate: CORS starts with credentials off, headers Content-Type,Authorization, max-age 1728000 (the middleware: credentials on, other headers, max-age 60); ETag in quotes with W/ support (the middleware: digest without quotes); RedirectHTTPFilter compares the path case-insensitively; AnalyticsHTTPFilter writes the PathInfo instead of controller and action; the session filters take a TMVCSessionCookieFlags set ([scfHttpOnly, scfSecure], default [scfHttpOnly]) instead of the two Booleans HttpOnly and Secure of the old Use*SessionMiddleware, with the SessionCookieFlags(ASecure) helper to build it from a Boolean; RedirectHTTPFilter tells 302 and 301 apart with TMVCRedirectKind (rdkTemporary, the default, or rdkPermanent) and keeps or drops the query string with TMVCRedirectQuery (rdqPreserve, the default, or rdqDrop): in the filter signatures Booleans that do not explain themselves have been replaced by types that are self-explanatory (the boolean trap). The same goes for TraceHTTPFilter (TMVCTraceFlags set: tfLogAuthorization, tfLogNonTextBody), SwaggerHTTPFilter (TMVCSwaggerAuthentications set: sauBasic, sauBearer, in fifth position in place of the two Booleans of the middleware, so one parameter fewer) and the static files options (Mode: sfmFiles or sfmSPA; Flags: sffCaseSensitivePrefix). Still Booleans: AAllowsCredentials of CORSHTTPFilter, which mirrors the parameter of the same name in the CORS middleware, and SessionCookieFlags(ASecure), which converts a value read from the .env file. StaticFilesHTTPFilter has the single page application fallback off by default (in the middleware it is on): you turn it on with StaticFilesHTTPFilter('/', folder, sfmSPA) or with Mode := sfmSPA in the options (TMVCStaticFilesOptions): the filter lets the router decide and responds with index.html only to a GET or HEAD for which the application has no route at all, so it can sit on / with the API next to it (it needs AllowUnhandledAction = false, the default, and the router writes ROUTE NOT FOUND in the log for every client-side route); the third parameter of the simple form is the mode (TMVCStaticFilesMode), the index document is the fourth; the filters do not write the per-file log line that the middleware wrote for every file served, and StaticFilesHTTPFilter serves .webp, .woff, .woff2 and .ttf with the right type. CompressionHTTPFilter does not recompress a response that already has a Content-Encoding. SecurityHeadersHTTPFilter, ShutdownHTTPFilter, OpenAPIHTTPFilter, RangeMediaHTTPFilter and TraceHTTPFilter have the same default values as the middleware (TraceHTTPFilter returns the correlation id X-Request-ID, masks Authorization and logs the body up to 1024 bytes; the signature is TraceHTTPFilter(AMaxBodySize, ALogTag, AFlags, ACorrelationHeaderName), with AFlags added in third position); ActiveRecordHTTPFilter enables the additional connections for every instance (the middleware only for the first one in the process). RateLimitHTTPFilter with options: same options and same response as the middleware (429, Retry-After, JSON body).
  • Author: Daniele Teti, creator of DelphiMVCFramework.

Comments