从 golang 中传入的 https 请求中提取公用名

Extract Common Name from incoming https request in golang

我的 api 在网关后面,网关终止了来自客户端的 ssl 握手,并与我的 api 发起了单独的握手。任何客户都不应直接致电我的 api。我的要求是我必须从传入的 https 请求中提取通用名称并根据列表对其进行验证。

我是新手,使用这个例子https://venilnoronha.io/a-step-by-step-guide-to-mtls-in-go 作为我使用 https 构建 go 服务器的起点。

但不确定如何进一步提取证书链的 COMMON NAME from the leaf certificate

package main

import (
    "crypto/tls"
    "crypto/x509"
    "io"
    "io/ioutil"
    "log"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    // Write "Hello, world!" to the response body
    io.WriteString(w, "Hello, world!\n")
}

func main() {
    // Set up a /hello resource handler
    http.HandleFunc("/hello", helloHandler)

    // Create a CA certificate pool and add cert.pem to it
    caCert, err := ioutil.ReadFile("cert.pem")
    if err != nil {
        log.Fatal(err)
    }
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    // Create the TLS Config with the CA pool and enable Client certificate validation
    tlsConfig := &tls.Config{
        ClientCAs:  caCertPool,
        ClientAuth: tls.RequireAndVerifyClientCert,
    }
    tlsConfig.BuildNameToCertificate()

    // Create a Server instance to listen on port 8443 with the TLS config
    server := &http.Server{
        Addr:      ":8443",
        TLSConfig: tlsConfig,
    }

    // Listen to HTTPS connections with the server certificate and wait
    log.Fatal(server.ListenAndServeTLS("cert.pem", "key.pem"))

}

我应该能够 print the Common Name of the leaf certificate 进入证书链。

您可以从请求的 TLS 字段的 VerifiedChains 成员中检索它:

func helloHandler(w http.ResponseWriter, r *http.Request) {
    if r.TLS != nil && len(r.TLS.VerifiedChains) > 0 && len(r.TLS.VerifiedChains[0]) > 0 {
        var commonName = r.TLS.VerifiedChains[0][0].Subject.CommonName

        // Do what you want with the common name.
        io.WriteString(w, fmt.Sprintf("Hello, %s!\n", commonName))
    }

    // Write "Hello, world!" to the response body
    io.WriteString(w, "Hello, world!\n")
}

叶证书始终是链中的第一个。