Filters, guards and errors

Before a navigation opens its screen, filters may send it elsewhere: a RouteFilter returns null to go on, or a location to go to instead. With spring_boot_starter_flutter_security, @PreAuthorize on a screen is such a guard: nobody logged in goes to the login, and back after it. Unknown addresses show the not-found screen, and a navigation that fails shows the error screen.

Why

Who may open a screen is a rule of the app, not of each button that leads there. A filter decides once, for every way in: a tap, the address bar, a deep link, the back button. A guard written as @PreAuthorize("hasRole('ADMIN')") reads like a Spring method's.

Filters

// Only administrators open /admin/**; everyone else goes to the catalog.
@Component()
final class AdminOnly implements RouteFilter {
  AdminOnly(this.session);

  final Session session;

  @override
  RouteLocation? filter(RouteRequest request) =>
      request.state.matches('/admin/**') && !session.isAdmin
          ? RouteLocation('/catalog')
          : null;
}

Guarded screens

With the security starter, @PreAuthorize on a screen takes the expressions of method security:

@ScreenRoute('/admin', title: 'Admin')
@PreAuthorize("hasRole('ADMIN')")
class AdminPage extends StatelessWidget { ... }
spring:
  flutter:
    navigation:
      login: /login

The not-found screen

@ScreenRoute.notFound()
class NotFoundPage extends StatelessWidget {
  const NotFoundPage({super.key});

  @override
  Widget build(BuildContext context) =>
      Center(child: Text('Nothing at ${context.route.uri}'));
}

The error screen

A navigation that fails (a value that does not convert, such as ?page=abc for an int; a filter that throws; a guard that refuses) shows the error screen: .error(...) in Dart configuration, else a plain one. Its RouteState.error says why.

Refused addresses

An address with an encoded slash or backslash, a backslash, an encoded NUL, or a . / .. segment (once decoded) opens nothing: the app stays on its screen, or opens its first screen when it was opened by such a link. Such an address could otherwise stay on one route while its {*rest} value named a file of another route's folder, past that route's guard. Plain dot segments in a typed address are resolved first, so they reach the screen they name, guard included.

Every deep link goes through the routes, filters and guards included. @RouteInfo(link: false), or a path under spring.flutter.navigation.deep-links.exclude, keeps a screen from opening by a link; the app's first screen opens instead (see The web and deep links).

In Spring (Java)

A RouteFilter is a HandlerFilterFunction of RouterFunctions. @PreAuthorize is method security's, evaluated by the security starter.

See also