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

My api is behind a gateway and the gateway terminates the ssl handshake from client and initiate a separate handshake with my api. No client should call my api directly. My requirement is that I have to extract the Common Name from incoming https request and validate it against a list.

I am new to go and used this example https://venilnoronha.io/a-step-by-step-guide-to-mtls-in-go as my starting point to build a go server using https.

But not sure how can I move further to to extract COMMON NAME from the leaf certificate of the certificate chain.

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!
")
}

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"))

}

I should be able to print the Common Name of the leaf certificate coming in the certificate chain.

1个回答

You can retrieve it from the VerifiedChains member of the request's TLS field:

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!
", commonName))
    }

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

The leaf certificate is always the first one in the chain.

drghhp8706
drghhp8706 很高兴听到。 如果答案对您有帮助,则无论您的声誉如何,都可以通过单击复选标记接受它。
一年多之前 回复
dougang7521
dougang7521 感谢@ paul-griffiths,它起作用了。 不幸的是,由于我的stackoverflow信誉得分低,我无法更改您的答案的状态。
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问