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

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


Looking at the Dio docs, it seems like this is intentional behaviour.

All headers added to the request will be added to the redirection request(s). However, any body send with the request will not be part of the redirection request(s).

https://api.flutter.dev/flutter/dart-io/HttpClientRequest/followRedirects.html

However, I understand (and agree!) that this is generally undesirable behaviour. My solution is to manually follow the redirects myself, which is not very nice but works in a pinch.

    Response<String> response;    try {      response = await dio.get(        url,        options: Options(          // Your headers here, which might be your auth headers          headers: ...,          // This is the key - avoid following redirects automatically and handle it ourselves          followRedirects: false,        ),      );    } on DioError catch (e) {      final initialResponse = e.response;      // You can modify this to understand other kinds of redirects like 301 or 307      if (initialResponse != null && initialResponse.statusCode == 302) {        response = await dio.get(          initialResponse.headers.value("location")!, // We must get a location header if we got a redirect          ),        );      } else {        // Rethrow here in all other cases        throw e;      }    }