gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:00:39 25 4
gpt4 key购买 nike

我的 api 在网关后面,网关终止来自客户端的 ssl 握手,并启动与我的 api 的单独握手。没有客户应该直接调用我的 api。我的要求是我必须从传入的 https 请求中提取通用名称并根据列表对其进行验证。

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

但不确定如何进一步从证书链的叶证书中提取 COMMON NAME

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

}

我应该能够打印证书链中叶证书的通用名称

最佳答案

您可以从请求的 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")
}

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

关于go - 从 golang 中传入的 https 请求中提取公用名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56434602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com