Search code examples
flutterdartdio

How to remove Authorization header on redirect on any Flutter/Dart http client


I'm currently working on a project which like a lot of other projects works with s3 storage. In this case the storage is linked via the back-end.

The situation is like this, I can get the 'attachment' via an URL, lets say example.com/api/attachments/{uuid}. If the user is authorized (via the header Authorization) it should return a 302 statuscode and redirect to the s3 url. The problem is that after the redirect the Authorization header persists and the http client return a 400 response and it's because of the persisting Authorization header. Is there any way I can remove the Authorization header after redirect without catching the first request and firing a new one?

My http client code currently looks like this:

  @override
  Future get({
    String url,
    Map<String, dynamic> data,
    Map<String, String> parameters,
  }) async {
    await _refreshClient();
    try {
      final response = await dio.get(
        url,
        data: json.encode(data),
        queryParameters: parameters,
      );
      return response.data;
    } on DioError catch (e) {
      throw ServerException(
        statusCode: e.response.statusCode,
        message: e.response.statusMessage,
      );
    }
  }

  Future<void> _refreshClient() async {
    final token = await auth.token;
    dio.options.baseUrl = config.baseUrl;
    dio.options.headers.addAll({
      'Authorization': 'Bearer $token',
      'Accept': 'application/json',
    });
    dio.options.contentType = 'application/json';
  }

Solution

  • Good news! This has been fixed recently with Dart 2.16 / Flutter v2.10!

    Related bugs in dart issue tracker:

    Official announcement: https://medium.com/dartlang/dart-2-16-improved-tooling-and-platform-handling-dd87abd6bad1

    TLDR: upgrade to Flutter v2.10!