Basic HTTP Auth with Flutter the right way
1 min readAug 20, 2019
Within a Flutter app, I just tried to create a POST request to an REST API backend that requires HTTP Basic Auth using this piece of code that I have found on Stackoverflow due to lack of documentation.
String username = 'test';
String password = '123£';
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
print(basicAuth);
Response r = await get('https://api.somewhere.io',
headers: {'authorization': basicAuth});
print(r.statusCode);
print(r.body);
Since my abstraction required a header that was prebuilt somewhere else, I created it this way:
Map headers = {
'content-type': 'application/json',
'accept': 'application/json',
'authorization': basicAuth
};
However, somewhere within the POST request the following exception was thrown:
_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>' }, event: LoginButtonPressed { username: futzi, password: futz }, nextState: LoginLoading }
Turned out, the Map has do be created with real type hinting:
Map<String, String> headers = {
'content-type': 'application/json',
'accept': 'application/json',
'authorization': basicAuth
};
This works :)