Sub topic 14
Validating and securing incoming links
A deep link is input from outside your app. This chapter assumes you have a working go_router setup with /products/:id and a login redirect, and that you can parse a Uri in Dart. It covers who can send your app a link, what a link can safely contain, and the checks that belong in the handler.
Treat every link as untrusted input
A link that reaches your app may come from a message, a web page, a QR code, or another app on the device. Anyone can craft a URL, so a link is no more trustworthy than a form field on a website.
Two rules cover most of the risk:
- Validate the shape of every link before you act on it.
- Never let a link alone grant access or trigger an irreversible action.
What link verification does and does not prove
Verified HTTPS links (Android App Links and iOS Universal Links) prove one thing. The domain owner has authorized your app to open links for that domain. This protects against another app claiming the same links.
Custom schemes such as myapp://products/42 have no such protection. Any app can register the same scheme, and the operating system may let the user pick, or pick for them. A malicious app can then intercept links meant for yours. Do not send secrets, such as password-reset tokens, through a custom scheme.
Verification does not prove the content of a particular link is safe. On Android, an intent filter makes your activity reachable from other apps. Another app can send your activity an intent with any URI in it, whether or not that URI would pass domain verification. Your Dart code must therefore check the host, path, and parameters itself.
| Threat | Cause | Mitigation |
|---|---|---|
| Link hijacking | Another app registers your custom scheme | Use verified HTTPS links for anything sensitive |
| Unexpected host | Handler accepts any URI the platform delivers | Allowlist scheme and host in Dart |
| Malformed parameters | Route trusts `:id` or query values | Validate with strict patterns, show a fallback |
| Open redirect | Login `from` parameter is followed blindly | Accept only internal paths |
| Token leakage | Secrets in URLs end up in logs, history, or analytics | Use short-lived one-time tokens, never log full URIs |
| Forced actions | Opening a link performs a purchase or deletion | Show a confirmation screen, check authorization on the server |
Get the verification files right
Most verification failures are silent. The link opens in the browser and nothing reports why. Check these points:
- Android fingerprint.
sha256_cert_fingerprintsinassetlinks.jsonmust match the certificate that signed the installed build. If you use Play App Signing, Google re-signs your app, so list the app signing key from the Play Console. You can also list the upload key and your debug key, so local builds verify too. - Android verification timing. The system verifies
autoVerifylinks at install time. After you changeassetlinks.json, reinstall the app or trigger a re-check. - Android status. On Android 12 and later,
adb shell pm get-app-links com.example.appshows the verification state for each domain. - iOS file location. Serve
apple-app-site-associationover HTTPS at/.well-known/, without redirects and with a JSON response. - iOS caching. iOS fetches the file through an Apple-managed cache, so edits may take time to appear on devices.
- Narrow paths. List only the paths the app handles, such as
/products/*. A broad/*entry routes every URL on your domain into the app, including pages meant for the browser.
Allowlist the scheme, host, and path
Put one function between the platform and the router. It returns a clean location or null, so every entry point shares the same rules.
const _allowedHosts = {'example.com', 'www.example.com'};
final _productId = RegExp(r'^[0-9]{1,10}$');
/// Returns an internal location such as "/products/42?ref=email",
/// or null if the link should be rejected.
String? validateIncomingLink(Uri uri) {
if (uri.scheme != 'https') return null;
if (!_allowedHosts.contains(uri.host.toLowerCase())) return null;
if (uri.hasPort && uri.port != 443) return null;
if (uri.userInfo.isNotEmpty) return null; // https://[email protected] tricks
final segments = uri.pathSegments;
if (segments.isEmpty) return '/';
if (segments.length == 2 && segments[0] == 'products') {
if (!_productId.hasMatch(segments[1])) return null;
final ref = uri.queryParameters['ref'];
final safeRef = (ref != null && RegExp(r'^[a-z0-9_-]{1,32}$').hasMatch(ref))
? ref
: null;
return Uri(
path: '/products/${segments[1]}',
queryParameters: safeRef == null ? null : {'ref': safeRef},
).toString();
}
return null; // anything not listed is rejected
}The function builds a new location from validated pieces instead of forwarding the original string. Unknown query parameters are dropped. Reject by default and add routes one at a time.
Hosts are compared after toLowerCase(). Dart's Uri.parse already lowercases the host, but the explicit call keeps the check correct if the input comes from elsewhere.
Use the validator in the manual handler
If you handle links yourself with app_links, call the validator instead of checking only the host:
import 'package:app_links/app_links.dart';
import 'package:go_router/go_router.dart';
final appLinks = AppLinks();
void listenForLinks(GoRouter router) {
appLinks.uriLinkStream.listen((uri) {
final target = validateIncomingLink(uri);
if (target == null) {
router.go('/not-found'); // or ignore silently
return;
}
router.go(target);
});
}This assumes a /not-found route exists. With go_router's default link handling, the platform URL goes straight to the router. In that setup, put the same checks in route redirect callbacks.
Validate parameters inside the route
Route-level checks protect you even when a link arrives through a path you did not anticipate, such as in-app navigation with context.go. Return the fallback screen when a parameter is invalid:
GoRoute(
path: '/products/:id',
builder: (context, state) {
final id = state.pathParameters['id']!;
if (!RegExp(r'^[0-9]{1,10}$').hasMatch(id)) {
return NotFoundScreen(uri: state.uri);
}
return ProductScreen(
id: int.parse(id),
ref: state.uri.queryParameters['ref'],
);
},
),Parse values into types (int, enums) at this boundary. A typed int cannot carry an injected string into a database query, a file path, or a web view URL further down.
Fix the open redirect in the login flow
The login redirect from the earlier chapter stores the original link in ?from=. If the login screen later navigates to whatever from contains, an attacker can craft https://example.com/login?from=https://evil.com, or hide a different destination in the value. The same applies to any url or next parameter that your app opens.
Accept only internal paths:
String? safeInternalPath(String? raw) {
if (raw == null || raw.isEmpty) return null;
if (!raw.startsWith('/') || raw.startsWith('//') || raw.contains('\\')) {
return null;
}
final uri = Uri.tryParse(raw);
if (uri == null || uri.hasScheme || uri.hasAuthority) return null;
return validateIncomingLink(Uri.https('example.com', uri.path, uri.queryParameters.isEmpty ? null : uri.queryParameters));
}
// After a successful sign-in:
void onLoginSuccess(BuildContext context, String? from) {
context.go(safeInternalPath(from) ?? '/');
}The final call reuses the allowlist, so a from value can only lead to a route you already accept from outside.
Keep secrets and side effects out of links
- Tokens. If a link must carry a token, such as email verification, make it single-use and short-lived. The app should exchange it with your server and not treat the token itself as proof of identity.
- Logging. Query strings often contain tokens. Log the route name or a redacted URI, not the full string. Check your analytics and crash-reporting tools for URL capture.
- Actions. A link to
/orders/42/cancelmust not cancel anything when it opens. Navigate to a screen that asks the user to confirm. - Authorization. The app's checks control what the interface shows. The server decides what a user may read or change. A user who edits
/products/42to/products/43must get the same answer from the server as if they had tapped through the app.
Finally, test on a device with the commands from the testing chapter. Send both valid and invalid links with adb and simctl, and confirm the invalid ones land on the fallback screen without errors.
Exercise
Your login redirect appends ?from=<original link>. A tester signs in through https://example.com/login?from=//evil.com/phish, and the app opens an external site after login. What is wrong, and what is the fix?
Show answer
The login screen follows from without checking it. //evil.com/phish looks like a path but is a scheme-relative URL with the authority evil.com. Pass from through a check like safeInternalPath, which rejects values that start with //, contain a backslash, or have a scheme or authority. Then validate the result against the allowlist and fall back to / when the check fails.
Exercise
A password-reset flow sends myapp://reset?token=abc123. Give two reasons this is risky and name a safer design.
Show answer
Any other app can register the myapp scheme and capture the link and its token, and the full URL may be logged or stored in history. A safer design uses a verified HTTPS link such as https://example.com/reset?token=..., opens it only in your app through App Links or Universal Links, and makes the token single-use and short-lived so the server rejects reuse and late use.