首頁 > 後端開發 > Golang > 主體

在 Golang 中如何使用 HTTP 進行驗證?

WBOY
發布: 2024-06-03 09:09:57
原創
654 人瀏覽過

在 Go 中,身份驗證方法包括:基本身份驗證:使用使用者名稱和密碼,驗證程式碼在文章中展示。 Bearer 令牌驗證:使用令牌作為憑證,驗證程式碼在文章中顯示。 OAuth 2.0 身份驗證:一種授權協議,驗證程式碼在文章中展示。實戰範例:針對所有路由啟用基本驗證的程式碼在文章中提供。

在 Golang 中如何使用 HTTP 进行身份验证?

在 Go 中使用 HTTP 進行驗證

在 Go 中使用 HTTP 進行驗證至關重要,以保護應用程式並驗證使用者身分。以下是 Go 中幾種常用身份驗證方法的指南,包括實戰案例。

基本驗證

基本驗證是最簡單的身份驗證方法,使用使用者名稱和密碼進行身份驗證。

func BasicAuth(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        username, password, ok := r.BasicAuth()
        if !ok || username != "user" || password != "password" {
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }

        next.ServeHTTP(w, r)
    })
}
登入後複製

Bearer 令牌驗證

Bearer 令牌驗證使用令牌作為憑證。

func BearerAuth(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := r.Header.Get("Authorization")
        if token != "Bearer my-token" {
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }

        next.ServeHTTP(w, r)
    })
}
登入後複製

OAuth 2.0 身份驗證

OAuth 2.0 是一種廣泛使用的授權協議,允許使用者授權第三方應用程式存取其資料。

func OAuth2Auth(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := r.URL.Query().Get("access_token")
        if token != "my-access-token" {
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }

        next.ServeHTTP(w, r)
    })
}
登入後複製

實戰案例

假設您有一個HTTP 路由器,您希望針對所有路由啟用基本驗證:

import (
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, authenticated user!"))
    })

    // Use BasicAuth middleware to protect all routes
    loggedRouter := BasicAuth(router)

    log.Fatal(http.ListenAndServe(":8080", loggedRouter))
}
登入後複製

現在,只要有人嘗試存取根路由(http://localhost:8080/),他們就會被要求輸入使用者名稱和密碼,否則他們將收到401 Unauthorized 回應。

以上是在 Golang 中如何使用 HTTP 進行驗證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!