My Flutter request returns 401 Unauthorized, but the same call works in Postman
Response status code: 401Short answer
401 in the app and 200 in Postman means the two requests differ. Compare them header by header. The usual culprits are a missing or wrongly formatted Authorization header, a token that is empty or expired by the time the call runs, or a redirect to another domain that strips Authorization.
Fix it fast
1Find out which cause you have
Print what the app really sends, then copy those values into Postman. If Postman now fails too, the difference is in the header. If it still passes, look at redirects.
final headers = {'Authorization': 'Bearer $token', 'Accept': 'application/json'}; print(headers); final res = await http.get(Uri.parse('https://api.example.com/api/user'), headers: headers); print('${res.statusCode} ${res.body}');2Match what you see, then jump to its fix
- 1
The printed header shows null, an empty token, or no Bearer prefixThe Authorization header is missing or in the wrong formatFix - 2
Postman uses a token you pasted; the app uses the one it got at loginThe token is a different one from the token Postman usesFix - 3
The server answers 301 or 302 first, for example from http to https, or from a bare domain to wwwA redirect to another domain drops the Authorization headerFix
- 1
What does the error look like?
Response status code: 401
Cause 1 of 3
The Authorization header is missing or in the wrong format
1Check
Sanctum reads API tokens from the Authorization header, as a Bearer token. A header that holds only the bare token, or a null from storage that was not loaded yet, is rejected.
print(token == null || token.isEmpty);2Fix
Load the token before building the request, and send it as Bearer.
final token = await storage.read(key: 'token');
final res = await http.get(
Uri.parse('https://api.example.com/api/user'),
headers: {'Authorization': 'Bearer $token', 'Accept': 'application/json'},
);3Verify
The status is 200 and the body holds the user.
print(res.statusCode);Confirmed by laravel.com
Cause 2 of 3
The token is a different one from the token Postman uses
1Check
Sanctum tokens can be revoked by deleting them from the database, so a stored token can stop working. Log in through the app, print the token it receives, and use that exact token in Postman.
print(loginResponse.body);2Fix
Issue a new token for the device at login and replace the stored one.
// Laravel
return $user->createToken($request->device_name)->plainTextToken;3Verify
The token returned at login works in both the app and Postman.
curl -H "Authorization: Bearer <token>" -H "Accept: application/json" https://api.example.com/api/userConfirmed by laravel.com
Cause 3 of 3
A redirect to another domain drops the Authorization header
1Check
dart:io follows redirects automatically, but sensitive headers such as Authorization are skipped when the redirect goes to a domain that is not the same host or a subdomain.
curl -I http://api.example.com/api/user2Fix
Call the final URL directly, so no cross-domain redirect happens.
final res = await http.get(
Uri.parse('https://www.example.com/api/user'),
headers: {'Authorization': 'Bearer $token'},
);3Verify
curl -I on the new URL shows no redirect and the app gets 200.
curl -I https://www.example.com/api/userConfirmed by api.flutter.dev
How do I stop it coming back?
- Build the Authorization header in one place, with a test that fails on a null token.
- Store the base URL as the final https address so no redirect happens.
- Send Accept: application/json on every API call.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- Spotless LaundryAn on-demand laundry app: Flutter on a Laravel back end, with Firebase for live updates.
- EZ EstimaterConstruction quoting and job tracking for contractors, on a Laravel and Firebase stack.
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
Related fixes
Mobile apps
AudioCache has no play method after updating audioplayers
The method 'play' isn't defined for the type 'AudioCache'.
Since audioplayers 1.0, AudioCache only turns asset files into local files and caches them.
2 causes, each with a fixMobile apps
Flutter Bloc throws that emit was called after the event handler completed
emit was called after an event handler completed normally.
Each on<Event> handler gets its own Emitter, and it stops working the moment the handler's returned Future completes.
2 causes, each with a fixMobile apps
analysis_options.yaml: the URI it includes can't be found
include_file_not_found
The analyzer reports include_file_not_found when the file named after include: in analysis_options.yaml does not resolve.
2 causes, each with a fixMobile apps
Dart error: the body might complete normally and return null for a non-nullable type
body_might_complete_normally
Dart found a path through your function or callback that reaches the closing brace without a return.
3 causes, each with a fixMobile apps
Dart throws ConcurrentModificationError while looping over a list
ConcurrentModificationError
Dart throws this when a collection changes size while something iterates it.
2 causes, each with a fixMobile apps
Dart cannot turn a compact timestamp like 20201101153000 into a DateTime
FormatException: Invalid date format
DateTime.parse accepts a subset of ISO 8601, and a time part must be introduced by T or a space.
2 causes, each with a fix