Sub topic 6
Sending headers and authentication tokens
This chapter assumes you can already send a GET request with the http package and decode the JSON response. You should also be comfortable with async/await and with passing a Map as a named argument. Here you will learn how to attach headers to requests, send credentials in the common schemes, and handle a rejected token.
What headers do
An HTTP header is a name and value pair sent before the body. Headers describe the request: what format you want back, what format you are sending, and who you are. The http package takes them as a Map<String, String> in the headers argument of every request method.
| Header | Direction | Purpose |
|---|---|---|
| `Accept` | Request | The response format you can handle, such as `application/json` |
| `Content-Type` | Request or response | The format of the body, such as `application/json; charset=UTF-8` |
| `Authorization` | Request | Credentials that identify the caller |
| `User-Agent` | Request | The client making the call |
| `Retry-After` | Response | How long to wait before trying again, sent with 429 and some 503 responses |
Header names are case-insensitive in HTTP. The http package respects that when it reads request headers. In responses it lowercases every name, so you read response.headers['content-type'], not 'Content-Type'.
Sending a bearer token
Most JSON APIs use the Bearer scheme. The Authorization header holds the word Bearer, a space, and the token that the login endpoint issued.
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<Map<String, dynamic>> fetchProfile(
http.Client client,
String token,
) async {
final uri = Uri.https('api.example.com', '/v1/me');
final response = await client.get(
uri,
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer $token',
},
);
if (response.statusCode != 200) {
throw Exception('Failed to load profile: ${response.statusCode}');
}
return jsonDecode(response.body) as Map<String, dynamic>;
}Every request that needs authentication must carry the header. The server keeps no memory of earlier requests from your app, so a token sent once does not authenticate later calls.
Other schemes
Some services use different schemes. The header or query parameter name comes from the service's documentation.
import 'dart:convert';
Map<String, String> basicAuthHeaders(String user, String password) {
final credentials = base64Encode(utf8.encode('$user:$password'));
return {'Authorization': 'Basic $credentials'};
}
Map<String, String> apiKeyHeaders(String key) => {'X-API-Key': key};Basic authentication only encodes the credentials with Base64. It does not encrypt them, so use it over HTTPS only. A request to an http:// address sends the credentials in the clear.
Where the token comes from
Do not hardcode tokens in source files. Keep two kinds of values apart.
- User tokens. These are issued at login and belong to one person. Store them with a platform keystore wrapper such as the
flutter_secure_storagepackage, which uses Keychain on iOS and encrypted storage on Android. Avoid plainSharedPreferencesfor these. - App-level keys. These identify your app to a service. You can inject them at build time, as shown below, but they end up inside the compiled app and can be extracted. Treat them as identifiers, not secrets.
const apiKey = String.fromEnvironment('API_KEY');Run the app with flutter run --dart-define=API_KEY=your-key. Keep real secrets, such as a database password or a payment secret key, on a server that your app calls.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const _storage = FlutterSecureStorage();
Future<String?> readAccessToken() => _storage.read(key: 'access_token');Reading from storage is asynchronous. That matters in the next section, because the code that adds the header has to wait for the token.
Adding the header in one place
If you write 'Authorization': 'Bearer $token' in every function, one mistake or one scheme change forces edits everywhere. The http package lets you wrap a client by subclassing http.BaseClient. You override only send, and every method on the wrapper (get, post and the rest) goes through it.
import 'package:http/http.dart' as http;
class AuthClient extends http.BaseClient {
AuthClient(this._inner, this._readToken);
final http.Client _inner;
final Future<String?> Function() _readToken;
@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
final token = await _readToken();
if (token != null) {
request.headers['Authorization'] = 'Bearer $token';
}
return _inner.send(request);
}
@override
void close() => _inner.close();
}You create it once, for example AuthClient(http.Client(), readAccessToken), and pass it wherever a http.Client is expected. The fetchPost function from earlier chapters then works unchanged. The next chapters on structuring an API client build on this idea.
When the server rejects the token
Two statuses look alike and mean different things.
- 401 Unauthorized means the server does not accept your credentials. The token is missing, malformed or expired. Getting a fresh token can fix it.
- 403 Forbidden means the server knows who you are and refuses the action. A new token will not help. Show a "not allowed" message.
Access tokens usually expire after minutes or hours. Many APIs also issue a longer-lived refresh token that you exchange for a new access token. A common pattern is to retry once after a 401.
import 'package:http/http.dart' as http;
abstract class TokenStore {
Future<String?> readAccessToken();
/// Exchanges the refresh token for a new access token.
/// Returns null if the session cannot be renewed.
Future<String?> refresh();
}
Future<http.Response> getAuthorized(
http.Client client,
Uri uri,
TokenStore store,
) async {
Future<http.Response> attempt(String? token) => client.get(
uri,
headers: {
'Accept': 'application/json',
if (token != null) 'Authorization': 'Bearer $token',
},
);
var response = await attempt(await store.readAccessToken());
if (response.statusCode == 401) {
final fresh = await store.refresh();
if (fresh != null) {
response = await attempt(fresh);
}
}
return response;
}The retry happens at most once. If the second response is also 401, the function returns it, and the caller should send the user to the login screen. Retrying in a loop can lock the account or hammer the server.
Concurrent refreshes
If three requests fail with 401 at the same moment, three refresh calls start. Many servers invalidate a refresh token after one use, so the second and third calls can fail and log the user out. The usual fix is to keep the in-flight refresh Future in a field and have every waiting request await that same Future. The interceptors chapter returns to this problem with Dio.
Reading response headers
Response headers arrive in response.headers, a map with lowercase keys.
import 'package:http/http.dart' as http;
Duration? retryDelay(http.Response response) {
final value = response.headers['retry-after'];
final seconds = value == null ? null : int.tryParse(value);
return seconds == null ? null : Duration(seconds: seconds);
}Retry-After can also hold an HTTP date instead of a number of seconds. The code above ignores that form and returns null for it. If the API you use sends dates, parse them with HttpDate.parse from dart:io. That library is not available on the web.
Platform and security notes
- Flutter web. The browser enforces CORS (cross-origin resource sharing). An
Authorizationheader, or aContent-Typeofapplication/json, makes the browser send a preflightOPTIONSrequest first. The server must answer withAccess-Control-Allow-Headerslisting those headers. When a call works on a phone but fails on web with no useful Dart error, the cause is almost always the server's CORS configuration. Browsers also forbid setting some headers, such asUser-Agent, from code. - Logging. Do not print full headers in logs. A logged
Authorizationvalue is a valid credential for as long as the token lives. - HTTPS. Build URLs with
Uri.https. Sending a token over plain HTTP exposes it to anyone on the network path. - Token in the URL. Avoid
?token=...query parameters. URLs end up in server logs and browser history, and headers do not.
Testing the header
MockClient receives the outgoing request, so a test can assert that the header is present without any network.
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
void main() {
test('fetchProfile sends the bearer token', () async {
final client = MockClient((request) async {
expect(request.headers['Authorization'], 'Bearer abc123');
expect(request.headers['Accept'], 'application/json');
return http.Response('{"name": "Ada"}', 200);
});
final profile = await fetchProfile(client, 'abc123');
expect(profile['name'], 'Ada');
});
}If the code under test forgets the header, the expect inside the handler fails the test.
Common mistakes
- Writing
Bearerwithout the space, or with the token in quotes. The server answers 401 and the cause is hard to see. - Passing a
Mapasbodywhile also setting a JSONContent-Type. The package then form-encodes the map. SendjsonEncode(map)as the body instead, as in the POST example from the previous chapter. - Reading a token once at app start and caching it forever. It expires and every call starts failing. Read the current value on each request, or refresh as shown above.
- Treating 403 like 401. Refreshing the token does not help when the user lacks permission.
Exercise
A request returns 401 and your code refreshes the token and retries. The retry also returns 401. What should the code do, and why should it not retry again?
Show answer
Return the second 401 to the caller, which should treat the session as ended and send the user to the login screen. A new token did not fix the problem, so something else is wrong, such as a revoked account or a rejected refresh token. Looping would send many failing requests and could trigger rate limiting or account lockout.
Exercise
You add an Authorization header to a request in a Flutter web build, and the call now fails in the browser with a CORS error, while the same code works on Android. What causes this, and where is the fix?
Show answer
A custom Authorization header makes the browser send a preflight OPTIONS request, and the server must allow that header through Access-Control-Allow-Headers. Android does not enforce CORS. The fix belongs on the server's CORS configuration, not in the Dart code.