11 Membuat Middleware Basic Authentication HTTP Router pada Golang
Basic Authentication is a simple authentication method where the client sends credentials (username and password) in the header of each HTTP request. In this article, we will learn how to create Basic Authentication middleware in Golang using the httprouter library.
This article is intended for beginner programmers, providing detailed steps and explanations to facilitate understanding.
Prerequisites
- Basic understanding of Golang: Familiarity with functions, structures, and package operations.
- Golang installed: Ensure you have Go installed on your computer.
- Required library: Install the
github.com/julienschmidt/httprouterlibrary with the following command:
1go get github.com/julienschmidt/httprouterStep 1: Project Structure
Create the following project structure:
1project-root/
2├── main.go
3├── middleware/
4│ └── basic_auth.go
5├── handlers/
6│ └── user.goThe main.go file serves as the application’s entry point, while middleware/ and handlers/ are used to separate middleware and endpoint functions.
Step 2: Creating the Main File
Open main.go and add the following code:
1package main
2
3import (
4 "fmt"
5 "log"
6 "net/http"
7 "github.com/julienschmidt/httprouter"
8 "project-root/middleware"
9 "project-root/handlers"
10)
11
12func main() {
13 router := httprouter.New()
14
15 // Public endpoint without authentication
16 router.GET("/public", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
17 fmt.Fprint(w, "Public endpoint does not require authentication!\n")
18 })
19
20 // Private endpoint using Basic Authentication middleware
21 router.GET("/private", middleware.BasicAuth(handlers.PrivateHandler))
22
23 log.Println("Server running at http://localhost:8080")
24 log.Fatal(http.ListenAndServe(":8080", router))
25}The above code defines a public endpoint and a private endpoint protected by Basic Authentication middleware.
Step 3: Creating Basic Authentication Middleware
Open middleware/basic_auth.go and write the following code:
1package middleware
2
3import (
4 "encoding/base64"
5 "net/http"
6 "strings"
7 "github.com/julienschmidt/httprouter"
8)
9
10var validUsers = map[string]string{
11 "admin": "password123",
12 "user": "password456",
13}
14
15func BasicAuth(next httprouter.Handle) httprouter.Handle {
16 return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
17 authHeader := r.Header.Get("Authorization")
18 if authHeader == "" || !strings.HasPrefix(authHeader, "Basic ") {
19 http.Error(w, "Unauthorized", http.StatusUnauthorized)
20 return
21 }
22
23 // Decode Base64 credentials
24 payload, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHeader, "Basic "))
25 if err != nil {
26 http.Error(w, "Invalid authentication token", http.StatusUnauthorized)
27 return
28 }
29
30 cred := strings.SplitN(string(payload), ":", 2)
31 if len(cred) != 2 || !validateUser(cred[0], cred[1]) {
32 http.Error(w, "Invalid username or password", http.StatusUnauthorized)
33 return
34 }
35
36 // Proceed to the next handler if valid
37 next(w, r, ps)
38 }
39}
40
41func validateUser(username, password string) bool {
42 if pass, ok := validUsers[username]; ok {
43 return pass == password
44 }
45 return false
46}This middleware reads the Authorization header, decodes Base64-encoded credentials, and validates the username and password using the in-memory validUsers map.
Step 4: Creating the Private Endpoint Handler
Open handlers/user.go and add the following code:
1package handlers
2
3import (
4 "fmt"
5 "net/http"
6 "github.com/julienschmidt/httprouter"
7)
8
9func PrivateHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
10 fmt.Fprint(w, "Welcome to the private endpoint! You have successfully authenticated.\n")
11}This handler will only be accessible if the provided Basic Authentication credentials are valid.
Step 5: Testing the Application
Run the application using the following command:
1go run main.goTry accessing the following endpoints using tools like curl or Postman.
1. Public Endpoint (No Authentication Required)
1curl http://localhost:8080/publicResponse:
1Public endpoint does not require authentication!2. Private Endpoint (With Authentication)
To access the private endpoint, add an Authorization header with the Basic value followed by Base64-encoded username and password.
For example, for the username admin and password password123:
1curl -H "Authorization: Basic YWRtaW46cGFzc3dvcmQxMjM=" http://localhost:8080/privateIf valid, the response will be:
1Welcome to the private endpoint! You have successfully authenticated.If the credentials are incorrect, you will receive a 401 Unauthorized error response.
Conclusion
By following these steps, you have successfully created Basic Authentication middleware in Golang using httprouter. This middleware provides a simple way to protect API endpoints, though it is not secure for production environments unless used with HTTPS.
For better security, consider using more modern authentication methods such as OAuth or JWT in your production applications. Happy coding!