duanbanfei2875 2015-01-14 10:03
浏览 28
已采纳

如何在Go中访问客户的证书?

Below is my code for an HTTPS server in Go. The server requires the client to provide an SSL certificate, but doesn't verify the certificate (by design).

You can generate a private/public key pair as follows if you'd like to give it a try:

$ openssl genrsa -out private.pem 2048
$ openssl req -new -x509 -key private.pem -out public.pem -days 365

Does anyone know how I can access the client certificate in the handler? Let's say I would like to report some properties about the certificate the client presented back to the client.

Thanks, Chris.

package main

import (
    "fmt"
    "crypto/tls"
    "net/http"
)

const (
    PORT       = ":8443"
    PRIV_KEY   = "./private.pem"
    PUBLIC_KEY = "./public.pem"
)

func rootHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Nobody should read this.")
}

func main() {

    server := &http.Server{
        TLSConfig: &tls.Config{
            ClientAuth: tls.RequireAnyClientCert,
            MinVersion: tls.VersionTLS12,
        },
        Addr: "127.0.0.1:8443",
    }

    http.HandleFunc("/", rootHandler)
    err := server.ListenAndServeTLS(PUBLIC_KEY, PRIV_KEY)
    if err != nil {
        fmt.Printf("main(): %s
", err)
    }
}
  • 写回答

1条回答 默认 最新

  • duanhao5038 2015-01-14 12:07
    关注

    Seems r *http.Request has TLS *tls.ConnectionState field which in turn has PeerCertificates []*x509.Certificate field, so

    fmt.Fprint(w, r.TLS.PeerCertificates)
    

    probably can do

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案