38

In Angular, one can use the canActivate for route guarding.

In Flutter, how would one go about it? Where is the guard placed? How do you guard routes?

I'm thinking along the lines of this:

  • User logged in. Their token is stored in Shared Preference (the right way to store tokens? )
  • User closed the app.
  • User opens app again. As the application starts, it determines if user is logged in (perhaps a service that checks the storage for token), and then
  • If logged in, load the homepage route
  • If not logged in, load the login page
KhoPhi
  • 9,660
  • 17
  • 77
  • 128

6 Answers6

15

I was stumbling over this problem too and ended up using a FutureBuilder for this. Have a look at my routes:

final routes = {
  '/': (BuildContext context) => FutureBuilder<AuthState>(
    // This is my async call to sharedPrefs
    future: AuthProvider.of(context).authState$.skipWhile((_) => _ == null).first,
    builder: (BuildContext context, AsyncSnapshot<AuthState> snapshot) {
      switch(snapshot.connectionState) {
        case ConnectionState.done:
          // When the future is done I show either the LoginScreen 
          // or the requested Screen depending on AuthState
          return snapshot.data == AuthState.SIGNED_IN ? JobsScreen() : LoginScreen()
        default:
          // I return an empty Container as long as the Future is not resolved
          return Container();
      }
    },
  ),
};

If you want to reuse the code across multiple routes you could extend the FutureBuilder.

MasseElch
  • 166
  • 3
5

I don't think there is a route guarding mechanism per se, but you can do logic in the main function before loading the app, or use the onGenerateRoute property of a MaterialApp. One way to do that in your case is to await an asynchronous function that checks if the user is logged in before loading the initial route. Something like

main() {
  fetchUser().then((user) {
    if (user != null) runApp(MyApp(page: 'home'));
    else runApp(MyApp(page: 'login'));
  });
}

But you may also be interested in the way the Shrine app does it. They have the login page as the initial route in any case and remove it if the user is logged in. That way the user sees the login page until it has been determined whether or not they log in. I've included the relevant snippet below.

class ShrineApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Shrine',
      home: HomePage(),
      initialRoute: '/login',
      onGenerateRoute: _getRoute,
    );
  }

  Route<dynamic> _getRoute(RouteSettings settings) {
    if (settings.name != '/login') {
      return null;
    }

    return MaterialPageRoute<void>(
      settings: settings,
      builder: (BuildContext context) => LoginPage(),
      fullscreenDialog: true,
    );
  }
}

If you don't want them to see the login page at all if they are logged in, use the first approach and you can control the splash screen that shows before runApp has a UI by exploring this answer.

Jacob Phillips
  • 8,841
  • 3
  • 51
  • 66
  • Interesting. Will give it a try. – KhoPhi Jun 25 '18 at 18:58
  • 2
    You have to be careful with calling `runApp` after a delay (e.g. in a `Future` callback) if you want to localize the app. Flutter fails to switch the locale or load additional locales when `runApp` is not called instantly. Otherwise, I think this answer is great! – boformer Jun 25 '18 at 23:20
  • 1
    @boformer in that case it may be better to have a loading screen as an intiial route and choose where to go after knowing if the user is authed. – Jacob Phillips Jun 26 '18 at 07:35
4

You can use auto_route extension. This extension is awesome for dealing with routes and provides good way of using guards. Please refer to the documentation: https://pub.dev/packages/auto_route#route-guards

Rahmat Ali
  • 1,430
  • 2
  • 17
  • 29
  • Thanks. That's definitely something I'll keep in mind. – KhoPhi Jul 16 '20 at 00:22
  • While you supplied a possible solution, link-only answers are discouraged. As in your case, the link seems to be changed and is pointing no more to route-guards, and thus the answer does not help to understand how to achieve the goal of the question. Please update the link and provide some explanation with the corresponding code. – Mohammed Noureldin Jun 26 '21 at 18:54
2

I came up with the following solution for a web project, which allows me to easily introduce guarded routes without having to worry that an unauthorized user is able to access sensitive information.

The GuardedRoute class looks like this:

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:kandabis_core/core.dart' as core;

Widget _defaultTransitionsBuilder(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child) {

    return child;
}

class GuardedRoute extends PageRouteBuilder {

    GuardedRoute({
        @required final String guardedRoute,
        @required final String fallbackRoute,
        @required final Stream<bool> guard,
        @required final core.Router router,
        final RouteTransitionsBuilder transitionsBuilder = _defaultTransitionsBuilder,
        final bool maintainState = true,
        final Widget placeholderPage,
    })
    : super(
        transitionsBuilder: transitionsBuilder,
        maintainState: maintainState,
        pageBuilder: (context, animation, secondaryAnimation) =>

            StreamBuilder(
                stream: guard,
                builder: (context, snapshot) {

                    if (snapshot.hasData) {

                        // navigate to guarded route
                        if (snapshot.data == true) {

                            return router.routes[guardedRoute](context);
                        }

                        // navigate to fallback route
                        return router.routes[fallbackRoute](context);
                    }

                    // show a placeholder widget while the guard stream has no data yet
                    return placeholderPage ?? Container();
                }
            ),
    );
}

Using the guarded route is easy. You can define a guarded route and a fallback route (like a login page). Guard is a Stream which decides if the user can navigate to the guarded route. this is my Router class which shows how to use the GuardedRoute class:

class BackendRouter extends core.BackendRouter {

    BackendRouter(
        this._authenticationProvider,
        this._logger
        );

    static const _tag = "BackendRouter";

    core.Lazy<GlobalKey<NavigatorState>> _navigatorKey =

        core.Lazy(() => GlobalKey<NavigatorState>());

    final core.AuthenticationProvider _authenticationProvider;
    final core.Logger _logger;

    @override
    Map<String, WidgetBuilder> get routes => {

        core.BackendRoutes.main: (context) => MainPage(),
        core.BackendRoutes.login: (context) => LoginPage(),
        core.BackendRoutes.import: (context) => ImportPage(),
    };

    @override
    Route onGenerateRoute(RouteSettings settings) {

        if (settings.name == core.BackendRoutes.login) {

            return MaterialPageRoute(
                settings: settings,
                builder: routes[settings.name]
            );
        }

        return _guardedRoute(settings.name);
    }

    @override
    GlobalKey<NavigatorState> get navigatorKey => _navigatorKey();

    @override
    void navigateToLogin() {

        _logger.i(_tag, "navigateToLogin()");

        navigatorKey
            .currentState
            ?.pushNamed(core.BackendRoutes.login);
    }

    @override
    void navigateToImporter() {

        _logger.i(_tag, "navigateToImporter()");

        navigatorKey
            .currentState
            ?.pushReplacement(_guardedRoute(core.BackendRoutes.import));
    }

    GuardedRoute _guardedRoute(
         String route,
         {
             maintainState = true,
             fallbackRoute = core.BackendRoutes.login,
         }) =>

         GuardedRoute(
             guardedRoute: route,
             fallbackRoute: fallbackRoute,
             guard: _authenticationProvider.isLoggedIn(),
             router: this,
             maintainState: maintainState,
             placeholderPage: SplashPage(),
         );
}

And your application class looks like this:

class BackendApp extends StatelessWidget {

    @override
    Widget build(BuildContext context) {

        // get router via dependency injection
        final core.BackendRouter router = di.get<core.BackendRouter>();

        // create app
        return MaterialApp(
            onGenerateRoute: (settings) => router.onGenerateRoute(settings),
            navigatorKey: router.navigatorKey,
        );
    }
}
Cliffus
  • 1,481
  • 2
  • 11
  • 7
0

You can use flutter_modular package to do that. It´s a library that try to keep the same features than angular. Take a look of it documentation. Modular Docs

-1

My solution is to build in a route guard system, much like the other libraries out there but where we can still use the original Navigator where needed, open a modal as a named route, chain guards, and add redirects. Its really basic but can be built on quite easily.

It seems like a lot but you'll just need 3 new files to maintain along with your new guards:

- router/guarded_material_page_route.dart
- router/route_guard.dart
- router/safe_navigator.dart

// Your guards go in here
- guards/auth_guard.dart
...

First create a new class that extends MaterialPageRoute, or MaterialWithModalsPageRoute if you're like me and want to open the Modal Bottom Sheet package. I've called mine GuardedMaterialPageRoute

class GuardedMaterialPageRoute extends MaterialWithModalsPageRoute {
  final List<RouteGuard> routeGuards;

  GuardedMaterialPageRoute({
    // ScrollController is only needed if you're using the modals, as i am in this example.
    @required Widget Function(BuildContext, [ScrollController]) builder,
    RouteSettings settings,
    this.routeGuards = const [],
  }) : super(
    builder: builder,
    settings: settings,
  );
}

Your route guards will look like this:

class RouteGuard {
  final Future<bool> Function(BuildContext, Object) guard;

  RouteGuard(this.guard);

  Future<bool> canActivate(BuildContext context, Object arguments) async {
    return guard(context, arguments);
  }
}

You can now add GuardedMaterialPageRoutes to your router file like so:

class Routes {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case homeRoute:
        // These will still work with our new Navigator!
        return MaterialPageRoute(
          builder: (context) => HomeScreen(),
          settings: RouteSettings(name: homeRoute),
        );

      case locationRoute:
        // Following the same syntax, just with a routeGuards array now.
        return GuardedMaterialPageRoute(
          // Again, scrollController is only if you're opening a modal as a named route.
          builder: (context, [scrollController]) {
            final propertiesBloc = BlocProvider.of<PropertiesBloc>(context);
            final String locationId = settings.arguments;

            return BlocProvider(
              create: (_) => LocationBloc(
                locationId: locationId,
                propertiesBloc: propertiesBloc,
              ),
              child: LocationScreen(),
            );
          },
          settings: RouteSettings(name: locationRoute),
          routeGuards: [
            // Now inject your guards, see below for what they look like.
            AuthGuard(),
          ]
        );
     ...

Create your async guard classes like so, as used above in our router.

class AuthGuard extends RouteGuard {
  AuthGuard() : super((context, arguments) async {
    final auth = Provider.of<AuthService>(context, listen: false);
    const isAnonymous = await auth.isAnonymous();
    return !isAnonymous;
  });
}

Now you'll need a new class that handles your navigation. Here you check if you have access and simply run through each guard:

class SafeNavigator extends InheritedWidget {

  static final navigatorKey = GlobalKey<NavigatorState>();

  @override
  bool updateShouldNotify(SafeNavigator oldWidget) {
    return false;
  }

  static Future<bool> popAndPushNamed(
    String routeName, {
    Object arguments,
    bool asModalBottomSheet = false,
  }) async {
    Navigator.of(navigatorKey.currentContext).pop();
    return pushNamed(routeName, arguments: arguments, asModalBottomSheet: asModalBottomSheet);
  }

  static Future<bool> pushNamed(String routeName, {
    Object arguments,
    bool asModalBottomSheet = false,
  }) async {
    // Fetch the Route Page object
    final settings = RouteSettings(name: routeName, arguments: arguments);
    final route = Routes.generateRoute(settings);

    // Check if we can activate it
    final canActivate = await _canActivateRoute(route);

    if (canActivate) {
      // Only needed if you're using named routes as modals, under the hood the plugin still uses the Navigator and can be popped etc.
      if (asModalBottomSheet) {
        showCupertinoModalBottomSheet(
            context: navigatorKey.currentContext,
            builder: (context, scrollController) =>
                (route as GuardedMaterialPageRoute)
                    .builder(context, scrollController));
      } else {
        Navigator.of(navigatorKey.currentContext).push(route);
      }
    }

    return canActivate;
  }

  static Future<bool> _canActivateRoute(MaterialPageRoute route) async {
    // Check if it is a Guarded route
    if (route is GuardedMaterialPageRoute) {
      // Check all guards on the route
      for (int i = 0; i < route.routeGuards.length; i++) {
        // Run the guard
        final canActivate = await route.routeGuards[i]
            .canActivate(navigatorKey.currentContext, route.settings.arguments);

        if (!canActivate) {
          return false;
        }
      }
    }

    return true;
  }
}

To make it all work you will need to add the SafeNavigator key to your Material app:

MaterialApp(
  navigatorKey: SafeNavigator.navigatorKey,
  ...
)

And now you can navigate to your routes and check if you have access to them like this:

// Opens a named route, either Guarded or not.
SafeNavigator.pushNamed(shortlistRoute);
// Opens a named route as a modal
SafeNavigator.pushNamed(shortlistRoute, asModalBottomSheet: true);
// Pops the current route and opens a named route as a modal
SafeNavigator.popAndPushNamed(shortlistRoute, asModalBottomSheet: true);
Dustin Silk
  • 4,320
  • 5
  • 32
  • 48
  • A value of type 'GuardedMaterialPageRoute' can't be returned from method 'generateRoute' because it has a return type of 'Route' – BartusZak Jan 13 '21 at 09:36