I have a project to build an app in Flutter and I have to login using Basic Auth and retrofit for the Api requests. I have searched everywhere and I haven't found anything that can help me on how to combine these two. Nothing that I've done so far was succesful. Can anyone help me or show me documentation that can help me?
CodePudding user response:
In Android We can do Basic auth like this:
// concatenate username and password with colon for authentication
String credentials = username ":" password;
// create Base64 encodet string
final String basic =
"Basic " Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
builder.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Authorization", basic);
request.addHeader("Accept", "application/json");
}
});
so maybe possible we can do like this also in flutter
var auth = 'Basic ' base64Encode(utf8.encode('$username:$password'));
Future<Response> callAPI(param) async {
await dio.post('/api/test',
data: {'param': param},
options: Options(headers: <String, String>{'authorization': auth}));
}
CodePudding user response:
You can use this code for basic request for auth.And if you want to return response, you can use something else instead of void. Like String or dynamic for return response
import 'package:http/http.dart' // import this
Future<void> sendRequest (dynamic baseUrl...)async{
var response = await http.post(
Uri.parse(baseUrl).replace(queryParameters: queryParameters),
headers: header,
body: json ?? jsonEncode(request),
);
}