简体   繁体   中英

How to Bypass SSL Certificate Verification in flutter?

How to Bypass SSL Certificate Verification in flutter? Error: Handshake Exception: Handshake error in client(OS Error:CERTIFICATE_VERIFY_FAILED:self signed certificate(handshake.cc:345)

You need to configure your HttpService to work with Self-Signed SSL local servers. Like this:


import 'dart:io';
import 'dart:convert';
class HttpService {
  Future<dynamic> sendRequestToServer(dynamic model, String                         reqType, bool isTokenHeader, String token) async {
      HttpClient client = new HttpClient();
      client.badCertificateCallback =((X509Certificate cert, String  host, int port) => true);
      HttpClientRequest request = await         client.postUrl(Uri.parse("https://${serverConstants.serverUrl}$reqType"));
      request.headers.set('Content-Type', 'application/json');
      if(isTokenHeader){
         request.headers.set('Authorization', 'Bearer $token');
      }
     request.add(utf8.encode(jsonEncode(model)));
     HttpClientResponse result = await request.close();
     if(result.statusCode == 200) {
        return jsonDecode(await result.transform(utf8.decoder)
        .join());
     } else {
        return null;
     }
   }
}

Read more from here .

It seems that you are using a self signed certificate, which is not trusted by the OS. You can set it as trusted following these steps:

Create a class that overrides HttpOverrides in the following way:

class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext context) {
    return super.createHttpClient(context)
          ..badCertificateCallback = (X509Certificate cert, String host, int port) {
            //add your certificate verification logic here
            return true;
          };
  }
}

Then, in your main method, instance your class and set it as the global HttpOverride:

HttpOverrides.global = new DevHttpOverrides();

If badCertificateCallback returns true it will accept all bad certificates; if returns false it will reject a bad certificate.

link. https://stackoverflow.com/a/66268556/11738366

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM