亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go:通過證書使用經過身份驗證的客戶端驗證后續的 http 請求

Go:通過證書使用經過身份驗證的客戶端驗證后續的 http 請求

Go
桃花長相依 2022-05-23 17:02:53
我目前正在編寫一個 HTTP 服務器(net/http),它托管多個端點并在訪問這些端點之前需要客戶端身份驗證(步驟 1)。成功驗證后,服務器會發出一個短期令牌,然后客戶端使用該令牌訪問這些端點。當客戶端發送令牌(通過 HTTP 標頭)時,在每個處理函數的開頭都有一段代碼來檢查客戶端是否經過身份驗證并且提供的令牌是有效的。我正在尋找一個可以攔截和驗證客戶端而不是isAuthenticated(r)從每個端點函數調用的鉤子/包裝器。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)        }}
查看完整描述

1 回答

?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

您可以創建一個可以包裝 a 的函數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.HandlerFuncs 周圍來使用它(顯然只有那些需要身份驗證的):


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)

        }

}

這樣,您的處理程序僅在返回該請求時才被調用 (by handleAuth) ,而不會在所有處理程序中復制代碼。isAuthenticatedtrue


查看完整回答
反對 回復 2022-05-23
  • 1 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號