Home  >  Article  >  Backend Development  >  How to use HTTP for authentication in Golang?

How to use HTTP for authentication in Golang?

WBOY
WBOYOriginal
2024-06-03 09:09:57695browse

In Go, authentication methods include: Basic authentication: using username and password, the verification code is shown in the article. Bearer Token Authentication: Use token as credential, verification code is shown in the article. OAuth 2.0 Authentication: An authorization protocol, the verification code is shown in the article. Practical example: The code to enable Basic Authentication for all routes is provided in the article.

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

Using HTTP for Authentication in Go

Using HTTP for authentication in Go is critical to secure your application and authenticate users. Here is a guide to several common authentication methods in Go, including practical examples.

Basic Authentication

Basic authentication is the simplest authentication method and uses a username and password to authenticate.

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 Token Authentication

Bearer Token Authentication uses a token as the credential.

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 Authentication

OAuth 2.0 is a widely used authorization protocol that allows users to authorize third-party applications to access their data.

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)
    })
}

Practical Case

Suppose you have an HTTP router and you want to enable Basic Authentication for all routes:

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))
}

Now, whenever someone tries to access the root route (http://localhost:8080/), they will be asked to enter their username and password, otherwise they will receive a 401 Unauthorized response.

The above is the detailed content of How to use HTTP for authentication in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn