onRequest method

  1. @override
Future onRequest(
  1. RequestOptions options,
  2. RequestInterceptorHandler handler
)

Called when the request is about to be sent.

Implementation

@override
Future onRequest(
  RequestOptions options,
  RequestInterceptorHandler handler,
) async {
  try {
    // iOS bug: Alamofire is failing to return parallel requests for certificate validation
    if (Platform.isIOS && secure != null) {
      await secure;
    }

    var baseUrl = options.baseUrl;

    if (options.path.contains('http') || options.baseUrl.isEmpty) {
      baseUrl = options.path;
    }

    secure = SSLCertificatePinning().check(
      serverURL: baseUrl,
      headerHttp: {},
      timeout: _timeout,
    );

    secure?.whenComplete(() => secure = null);
    final secureString = await secure ?? '';

    if (secureString.contains('CONNECTION_SECURE')) {
      return super.onRequest(options, handler);
    } else {
      handler.reject(
        DioException(
          requestOptions: options,
          error: CertificateNotVerifiedException(),
        ),
      );
    }
  } on Exception catch (e) {
    dynamic error;

    if (e is PlatformException && e.code == 'CONNECTION_NOT_SECURE') {
      error = const CertificateNotVerifiedException();
    } else if (e is PlatformException && e.code == 'DEBUG_CONFIG_FILE'){
      error = const DebugConfigFileException();
    }else if (e is PlatformException && e.code == 'EMPTY_CONFIG_FILE'){
      error = const ImproperSSLPinningConfig();
    }
    else {
      error = CertificateCouldNotBeVerifiedException(e);
    }

    handler.reject(
      DioException(
        requestOptions: options,
        error: error,
      ),
      callFollowingErrorInterceptor,
    );
  }
}