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

时间:2019-06-03 21:13:12

标签: go tls1.2 mutual-authentication

我的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进入证书链。

1 个答案:

答案 0 :(得分:2)

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

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

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