Skip to main content
Version: 2.8.x(Latest)

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

  1. Clone the repository:

    git clone https://github.com/gogf/examples.git
    cd examples/httpserver/basic-auth
  2. Install the dependencies:

    go mod tidy
  3. Run the application:

    go run main.go

Usage

  1. Start the server:

    go run main.go
  2. The server will start on port 8000.

  3. Access the protected resource:

  4. 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:

  1. Checks if the request contains valid Basic Authentication credentials
  2. 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
  3. 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