caCert, err := ioutil.ReadFile("client-ca.pem") if err != nil { log.Fatal(err) } caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) tlsConfig := &tls.Config{ ClientCAs: caCertPool, ClientAuth: tls.RequireAndVerifyClientCert, } listener, err := tls.Listen("tcp", "localhost:1234", tlsConfig) if err != nil { log.Fatal(err) } defer listener.Close() // Accept and handle client connections
caCert1, err := ioutil.ReadFile("client-ca1.pem") if err != nil { log.Fatal(err) } caCert2, err := ioutil.ReadFile("client-ca2.pem") if err != nil { log.Fatal(err) } caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert1) caCertPool.AppendCertsFromPEM(caCert2) tlsConfig := &tls.Config{ ClientCAs: caCertPool, ClientAuth: tls.RequireAndVerifyClientCert, } listener, err := tls.Listen("tcp", "localhost:1234", tlsConfig) if err != nil { log.Fatal(err) } defer listener.Close() // Accept and handle client connectionsIn this example, we read the contents of two PEM-encoded client CA certificate files ("client-ca1.pem" and "client-ca2.pem"), create a new CertPool, add both client CA certificates to it using the AppendCertsFromPEM method, and set Config.ClientCAs to the CertPool. This allows clients with certificates issued by either client CA to connect. Overall, the Config.ClientCAs field is useful when implementing mutual TLS authentication, where both clients and servers present certificates during the TLS handshake. It allows you to specify the trusted CAs that will be used to authenticate clients, and can be configured with one or more CA certificates.