登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-13 18:41:05 470浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《从 golang 中传入的 https 请求中提取通用名称》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

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

我是 go 新手,使用此示例 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")
}

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

理论要掌握,实操不能落!以上关于《从 golang 中传入的 https 请求中提取通用名称》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>