如何让 Go 接受用于 TLS 客户端身份验证的自签名证书?

我正在使用 AWS API Gateway 和 Go 后端。为了确保所有连接都通过 API Gateway,我需要使用 TLS 客户端身份验证(又名双向身份验证,相互身份验证)。


原则上,这适用于以下内容:


func enableClientAuth(server *http.Server, clientCertFile string) error {

    clientCert, err := ioutil.ReadFile(clientCertFile)

    if err != nil {

        return err

    }

    caCertPool := x509.NewCertPool()

    caCertPool.AppendCertsFromPEM(clientCert)


    tlsConfig := &tls.Config{

        ClientAuth: tls.RequireAndVerifyClientCert,

        ClientCAs:  caCertPool,

    }

    tlsConfig.BuildNameToCertificate()

    server.TLSConfig = tlsConfig

    return nil

}

我遇到的问题是这个错误:


tls:无法验证客户端的证书:x509:由未知机构签署的证书(可能是因为“x509:无效签名:父证书无法签署此类证书”,同时尝试验证候选机构证书“ApiGateway”)


这似乎是因为客户端证书是自签名的,但不是CA证书,Go不会接受签名。(这不是违背了自签名证书的目的吗?我见过的大多数自签名证书都不是 CA 证书。)不幸的是,我无法控制客户端证书的生成或发送方式;这一切都由 AWS 完成。我可以做些什么来在 ClientCAs 证书池中获取证书,从而导致 Go 接受 API Gateway 客户端证书?


翻阅古今
浏览 294回答 1
1回答

繁花如伊

即我需要在加载客户端证书结构后对其进行修改。这需要解码 PEM 并解析出证书。对于 API Gateway 客户端证书,我必须将BasicConstraintsValidand设置IsCA为 true 和KeyUsageto KeyUsageCertSign; 对于我本地生成的证书,我只需要后两个。enableClientAuth()在我的问题中修改func:func enableClientAuth(server *http.Server, clientCertFile string) error {    pemBytes, err := ioutil.ReadFile(clientCertFile)    if err != nil {        return err    }    pemBlock, _ := pem.Decode(pemBytes)    clientCert, err := x509.ParseCertificate(pemBlock.Bytes)    if err != nil {        return err    }    clientCert.BasicConstraintsValid = true    clientCert.IsCA = true    clientCert.KeyUsage = x509.KeyUsageCertSign    caCertPool := x509.NewCertPool()    caCertPool.AddCert(clientCert)    tlsConfig := &tls.Config{        ClientAuth: tls.RequireAndVerifyClientCert,        ClientCAs:  caCertPool,    }    tlsConfig.BuildNameToCertificate()    server.TLSConfig = tlsConfig    return nil}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go