Flutter web redirect user if not authentiacted

Issue

I have a GetMaterialApp with named routes to be used in Flutter web for a dashboard project. However, I am struggling to check whether the user is authenticated and redirect the user depending on the auth state. This is my App Code:

GetMaterialApp(
      initialBinding: InitialBinding(),
      debugShowCheckedModeBanner: false,
      theme: CustomTheme().getLightTheme,
      themeMode: ThemeMode.light,
      title: "----------",
      initialRoute: "/login",
      unknownRoute: GetPage(name: "/notfound", page: () => NotFoundPage()),
      getPages: [
        GetPage(name: "/login", page: () => Root()),
        GetPage(name: "/dashboard", page: () => Dashboard()),
      ],
    ),

I am using GetX to handle the authentication state. Therefore, I have access to the authentication state throughout the web app. The Root widget consists of a simple Obx to check the authentication state and send the user to the dashboard:

return Obx(() => (Get.find<AuthController>().loggedIn) ? Dashboard() : LoginScreen());

Sadly, that does not do the trick, as the url does not change, simply the content does. The url remains at /login.

I could simply call Get.toNamed("dashboard") when the user is logged in, but then the dashboard page would be exposed to the url, allowing the user to reach the /dashboard url even if he is not logged in.

I also do not want to create a check in every Widget or page I create, since that would be inefficient. Is there a way to check whether the user is logged in and, if not, redirect the user to the login page on every url entered?

Example:

Is there a way to generally check the auth-state and redirect the user accordingly using GetX?

Side Note: I am able to get the correct authentication state every time, that is not the problem, as I use GetX.

Short Summary:
Is it possible to check the auth state outside the actual widget (e.g. in the GetMaterialApp) and redirect any not-authenticated users to the login page, even if they type in the /dashboard url?

Solution

Use middleware for check if user is authenticated or not

GetMaterialApp(
      initialBinding: InitialBinding(),
      debugShowCheckedModeBanner: false,
      theme: CustomTheme().getLightTheme,
      themeMode: ThemeMode.light,
      title: "----------",
      initialRoute: "/dashboard",
      unknownRoute: GetPage(name: "/notfound", page: () => NotFoundPage()),
      getPages: [
        GetPage(name: "/login", page: () => Root()),
        GetPage(name: "/dashboard", page: () => Dashboard(), middleware: [AuthMiddleware()]),
      ],
    ),

class AuthMiddlware extends Middlware {
   RouteSetting? redirect(String? route) => !isAuthenticated ? RouteSetting(name="/login") : null;
}

Answered By – Pierre RAKOTODIMIMANANA

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *