HTTP Server Basic Authentication
Github Source: https://github.com/gogf/examples/tree/main/httpserver/basic-auth
Description
This example demonstrates how to implement HTTP Basic Authentication using the GoFrame
framework. Basic Authentication is a simple authentication mechanism that allows a server to request credentials from a client before granting access to protected resources.
The example shows how to:
- Set up a basic HTTP server with protected resources
- Implement Basic Authentication using GoFrame's built-in
BasicAuth
method - Handle authentication success and failure cases
- Customize the authentication realm message
Requirements
Structure
basic-auth/
├── README.MD # English documentation
├── README.ZH.MD # Chinese documentation
├── go.mod # Go module file
└── main.go # Main application entry point
Features
- Simple and secure HTTP Basic Authentication
- Automatic handling of authentication headers
- Customizable authentication realm message
- Clean separation of authentication logic
Setup
-
Clone the repository:
git clone https://github.com/gogf/examples.git
cd examples/httpserver/basic-auth -
Install the dependencies:
go mod tidy
-
Run the application:
go run main.go
Usage
-
Start the server:
go run main.go
-
The server will start on port 8000.
-
Access the protected resource:
- URL: http://127.0.0.1:8000/
- When prompted, enter the following credentials:
- Username:
user
- Password:
pass
- Username:
-
After successful authentication, you will see the message: "Authentication successful!"
Implementation Details
The server uses GoFrame's BasicAuth
method to implement HTTP Basic Authentication. This method:
- Checks if the request contains valid Basic Authentication credentials
- If credentials are missing or invalid, it automatically:
- Sets the
WWW-Authenticate
header with the specified realm - Returns a 401 Unauthorized status code
- Causes the browser to display an authentication dialog
- Sets the
- If authentication succeeds, it returns
true
and allows the handler to proceed with the protected content
The implementation is clean and requires minimal code:
if r.BasicAuth("user", "pass", "Please enter username and password") {
// Process after successful authentication
r.Response.Write("Authentication successful!")
}
// If authentication fails, the BasicAuth method handles the response automatically
Notes
- Basic Authentication transmits credentials in base64 encoding, which is not secure over plain HTTP
- For production use, always combine Basic Authentication with HTTPS
- The credentials in this example are hardcoded for demonstration purposes; in a real application, you should use a secure credential store