gpt4 book ai didi

http - Go:通过证书使用经过身份验证的客户端验证后续的 http 请求

转载 作者:行者123 更新时间:2023-12-01 22:15:00 24 4
gpt4 key购买 nike

我目前正在编写一个 HTTP 服务器(net/http),它托管多个端点并在访问这些端点之前需要客户端身份验证(步骤 1)。成功验证后,服务器会发出一个短期 token ,然后客户端使用该 token 访问这些端点。当客户端发送 token (通过 HTTP header )时,在每个处理函数的开头都有一段代码来检查客户端是否经过身份验证并且提供的 token 是有效的。我正在寻找一个可以拦截和验证客户端而不是调用 isAuthenticated(r) 的钩子(Hook)/包装器从每个端点功能。

func getMyEndpoint(w http.ResponseWriter, r *http.Request) {
if valid := isAuthenticated(r); !valid {
w.WriteHeader(http.StatusUnauthorized)
io.WriteString(w, "Invalid token or Client not authenticated."
return
}
...
}

func server() {

http.HandleFunc("/login", clientLoginWithCertAuth)
http.HandleFunc("/endpoint1", getMyEndpoint)
http.HandleFunc("/endpoint2", putMyEndpoint)

server := &http.Server{
Addr: ":443",
TLSConfig: &tls.Config{
ClientCAs: caCertPool,
ClientAuth: tls.VerifyClientCertIfGiven,
},
}

if err := server.ListenAndServeTLS("cert.pem", "key.pem"); err != nil {
panic(err)
}
}

最佳答案

您可以创建一个可以包装 http.HandlerFunc 的函数,例如像这样:

func handleAuth(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if valid := isAuthenticated(r); !valid {
w.WriteHeader(http.StatusUnauthorized)
io.WriteString(w, "Invalid token or Client not authenticated.")
return // this return is *very* important
}
// Now call the actual handler, which is authenticated
f(w, r)
}
}

现在您还需要注册您的处理程序以使用它,方法是将它包裹在您的另一个 http.HandlerFunc 周围。 s(只有那些显然需要认证的人):
func server() {
// No authentication for /login
http.HandleFunc("/login", clientLoginWithCertAuth)

// Authentication required
http.HandleFunc("/endpoint1", handleAuth(getMyEndpoint))
http.HandleFunc("/endpoint2", handleAuth(putMyEndpoint))

server := &http.Server{
Addr: ":443",
TLSConfig: &tls.Config{
ClientCAs: caCertPool,
ClientAuth: tls.VerifyClientCertIfGiven,
},
}

if err := server.ListenAndServeTLS("cert.pem", "key.pem"); err != nil {
panic(err)
}
}

这样,您的处理程序只有在 handleAuth 时才会被调用(由 isAuthenticated 调用)返回 true对于该请求,无需在所有请求中复制代码。

关于http - Go:通过证书使用经过身份验证的客户端验证后续的 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60945081/

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