Dart https request with ssl certificate please

后端 未结 2 1419
无人及你
无人及你 2020-12-17 04:19

I have the following Javascript code which works fine when I run it with nodejs. However, I would like to write something similar that works with Dart. I\'ve gone through th

2条回答
  •  太阳男子
    2020-12-17 04:46

    Sending a client certificate in your HTTPS request can now be done in Dart as easily as in node.js, starting with version 1.13.0. The client certificate and key, in PEM format, can be added to the default SecurityContext object, before you make your HTTPS request.

    Dart has now switched to using BoringSSL, a fork of OpenSSL maintained by Google. BoringSSL uses X509 certificates (the certificates used by SSL and TLS) stored in files in PEM format. The older versions of Dart used NSS, which had its own database of certificates and keys, that was maintained with command-line tools. Dart has changed some parameters of SecureSocket methods, and added a SecurityContext class.

    SecurityContext.defaultContext is an object that contains the built-in trusted roots of well-known certificate authorities, taken from Mozilla's database that they use for Firefox and NSS. So your client should use this object, and add the client certificate and private key to it, so they will be used to authenticate with the server that requests them:

    Future postWithClientCertificate() async {
      var context = SecurityContext.defaultContext;
      context.useCertificateChain('client-2048.crt');
      context.usePrivateKey('client-2048.key',
                            password:'keyfile_password');
      HttpClient client = new HttpClient(context: context);
    
      // The rest of this code comes from your question.
      var uri = "https://identitysso-api.betfair.com:443/api/certlogin";
      var data = 'username=xxxxxxxx&password=xxxxxxxx';
      var appKey = 'xxxxxxxxxxxx';
      var method = 'POST';
    
      var request = await client.openUrl(method,Uri.parse(uri))
      request.headers.set(HttpHeaders.CONTENT_TYPE,
                          'application/x-www-form-urlencoded');
      request.headers.set('X-Application', appKey);
      request.write(data);
      var response = await request.close();
      // Process the response.
    }
    

    The functions SecurityContext.useCertificateChain and SecurityContext.usePrivateKey are the same ones that are used to set the server certificate and key, for a SecureServerSocket, but when the context is used for a client connection, they specify the client certificate to be sent upon request.

提交回复
热议问题