Ash*_*Ash 3 go mutual-authentication tls1.2
我的 api 位于网关后面,网关终止来自客户端的 ssl 握手,并与我的 api 启动单独的握手。任何客户端都不应该直接调用我的 api。我的要求是我必须从传入的 https 请求中提取公用名并根据列表对其进行验证。
我是 Go 新手,并使用此示例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"))
}
Run Code Online (Sandbox Code Playgroud)
我应该能够print the Common Name of the leaf certificate进入证书链。
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")
}
Run Code Online (Sandbox Code Playgroud)
叶证书始终是链中的第一个证书。
| 归档时间: |
|
| 查看次数: |
2350 次 |
| 最近记录: |