Sub topic 13
Redirects and Authentication Guards
This chapter assumes Dart async and await, basic Flutter widgets, BuildContext, and the go_router package. A redirect is a routing decision that sends a requested location to another location. An authentication guard uses a redirect to keep users away from routes that require a signed-in user.
How a redirect works
A GoRouter redirect callback runs when the location changes. It receives the current router state and returns:
- A location such as
'/login'to redirect the user. nullto keep the current location.
The router must also re-run the callback when authentication changes. refreshListenable connects a ChangeNotifier to the router for this purpose.
caption: Authentication redirect flow
alt: A flowchart showing an unauthenticated user redirected to login and an authenticated user allowed into the requested page.
flowchart TD
A[User requests protected route] --> B{Is the user signed in?}
B -->|No| C[Redirect to /login]
B -->|Yes| D[Build the requested route]
C --> E[User signs in]
E --> F[Authentication notifier changes]
F --> G[Router re-runs redirect]
G --> DConfigure an authentication guard
The following example uses an app-defined AuthState. It extends ChangeNotifier, so calling notifyListeners causes go_router to check the redirect again.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class AuthState extends ChangeNotifier {
bool isLoggedIn = false;
void logIn() {
isLoggedIn = true;
notifyListeners();
}
void logOut() {
isLoggedIn = false;
notifyListeners();
}
}
final authState = AuthState();
final router = GoRouter(
refreshListenable: authState,
initialLocation: '/',
redirect: (context, state) {
final loggedIn = authState.isLoggedIn;
final onLoginPage = state.matchedLocation == '/login';
if (!loggedIn && !onLoginPage) {
return '/login';
}
if (loggedIn && onLoginPage) {
return '/';
}
return null;
},
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/login',
builder: (context, state) => const LoginScreen(),
),
],
);
class LoginScreen extends StatelessWidget {
const LoginScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sign in')),
body: Center(
child: ElevatedButton(
onPressed: () {
authState.logIn();
},
child: const Text('Sign in'),
),
),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: authState.logOut,
child: const Text('Sign out'),
),
),
);
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(routerConfig: router);
}
}
void main() {
runApp(const MyApp());
}The onLoginPage check prevents a redirect loop. Without it, an unauthenticated user who is sent to /login would immediately be sent to /login again. The second check prevents a signed-in user from remaining on the login page.
Preserve the requested location
A common improvement is to remember where the user wanted to go. Add the original location as a query parameter:
return '/login?from=${Uri.encodeComponent(state.uri.toString())}';After successful sign-in, read state.uri.queryParameters['from']. Validate that the destination is an internal route before navigating to it. Otherwise, an attacker could use the value as an external redirect.
Common errors
| Error | Result | Prevention |
|---|---|---|
| No `refreshListenable` | The router does not notice login changes | Pass the auth notifier |
| No login-page exception | Redirect loop | Check the current location |
| Authorization only in the client | Protected data may still be exposed | Check permissions on the server |
Exercise
Why does the redirect callback return null after checking both authentication cases?
Show answer
null tells go_router that no redirect is needed, so it can build the current route.