Skip to content

Commit 308b937

Browse files
committed
add basic auth example
1 parent 51cf91a commit 308b937

File tree

7 files changed

+351
-18
lines changed

7 files changed

+351
-18
lines changed

.ai-prompt.zh.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
## 新example模块生成README文档
55

6-
分析examples/httpserver/sse代码,并参考examples/httpserver/proxy的文档结构后完成以下工作:
6+
分析 examples/httpserver/basic-auth 代码,并参考examples/httpserver/proxy的文档结构后完成以下工作:
77
- 增加README.MD和README.ZH.MD文件。
88
- 文档中的关键词需要代码高亮。
99
- 如果需要展示目录结构,目录结构的代码高亮语言类型使用text。

httpserver/basic-auth/README.MD

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
---
2+
title: Basic Authentication
3+
slug: /examples/httpserver/basic-auth
4+
keywords: [http, server, basic auth, authentication, goframe]
5+
description: A Basic Authentication example using GoFrame framework
6+
hide_title: true
7+
---
8+
9+
# HTTP Server Basic Authentication
10+
11+
## Description
12+
13+
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.
14+
15+
The example shows how to:
16+
- Set up a basic HTTP server with protected resources
17+
- Implement Basic Authentication using GoFrame's built-in `BasicAuth` method
18+
- Handle authentication success and failure cases
19+
- Customize the authentication realm message
20+
21+
## Requirements
22+
23+
- [Go](https://golang.org/dl/) `1.22` or higher
24+
- [Git](https://git-scm.com/downloads)
25+
- [GoFrame](https://goframe.org)
26+
27+
## Structure
28+
29+
```text
30+
basic-auth/
31+
├── README.MD # English documentation
32+
├── README.ZH.MD # Chinese documentation
33+
├── go.mod # Go module file
34+
└── main.go # Main application entry point
35+
```
36+
37+
## Features
38+
39+
- Simple and secure HTTP Basic Authentication
40+
- Automatic handling of authentication headers
41+
- Customizable authentication realm message
42+
- Clean separation of authentication logic
43+
44+
## Setup
45+
46+
1. Clone the repository:
47+
```bash
48+
git clone https://github.com/gogf/examples.git
49+
cd examples/httpserver/basic-auth
50+
```
51+
52+
2. Install the dependencies:
53+
```bash
54+
go mod tidy
55+
```
56+
57+
3. Run the application:
58+
```bash
59+
go run main.go
60+
```
61+
62+
## Usage
63+
64+
1. Start the server:
65+
```bash
66+
go run main.go
67+
```
68+
69+
2. The server will start on port 8000.
70+
71+
3. Access the protected resource:
72+
- URL: http://127.0.0.1:8000/
73+
- When prompted, enter the following credentials:
74+
- Username: `user`
75+
- Password: `pass`
76+
77+
4. After successful authentication, you will see the message: "Authentication successful!"
78+
79+
## Implementation Details
80+
81+
The server uses GoFrame's `BasicAuth` method to implement HTTP Basic Authentication. This method:
82+
83+
1. Checks if the request contains valid Basic Authentication credentials
84+
2. If credentials are missing or invalid, it automatically:
85+
- Sets the `WWW-Authenticate` header with the specified realm
86+
- Returns a 401 Unauthorized status code
87+
- Causes the browser to display an authentication dialog
88+
3. If authentication succeeds, it returns `true` and allows the handler to proceed with the protected content
89+
90+
The implementation is clean and requires minimal code:
91+
92+
```go
93+
if r.BasicAuth("user", "pass", "Please enter username and password") {
94+
// Process after successful authentication
95+
r.Response.Write("Authentication successful!")
96+
}
97+
// If authentication fails, the BasicAuth method handles the response automatically
98+
```
99+
100+
## Notes
101+
102+
- Basic Authentication transmits credentials in base64 encoding, which is not secure over plain HTTP
103+
- For production use, always combine Basic Authentication with HTTPS
104+
- The credentials in this example are hardcoded for demonstration purposes; in a real application, you should use a secure credential store

httpserver/basic-auth/README.ZH.MD

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
---
2+
title: 基本认证
3+
slug: /examples/httpserver/basic-auth
4+
keywords: [http, 服务器, 基本认证, 身份验证, goframe]
5+
description: 使用 GoFrame 框架实现 HTTP 基本认证
6+
hide_title: true
7+
---
8+
9+
# HTTP 服务器基本认证
10+
11+
## 介绍
12+
13+
本示例展示了如何使用 `GoFrame` 框架实现 `HTTP` 基本认证(`Basic Authentication`)。基本认证是一种简单的认证机制,允许服务器在授予对受保护资源的访问权限之前请求客户端提供凭据。
14+
15+
示例展示了如何:
16+
- 设置带有受保护资源的基本 HTTP 服务器
17+
- 使用 `GoFrame` 内置的 `BasicAuth` 方法实现基本认证
18+
- 处理认证成功和失败的情况
19+
- 自定义认证领域(`realm`)消息
20+
21+
## 环境要求
22+
23+
- [Go](https://golang.org/dl/) `1.22` 或更高版本
24+
- [Git](https://git-scm.com/downloads)
25+
- [GoFrame](https://goframe.org)
26+
27+
## 目录结构
28+
29+
```text
30+
basic-auth/
31+
├── README.MD # 英文文档
32+
├── README.ZH.MD # 中文文档
33+
├── go.mod # Go 模块文件
34+
└── main.go # 主程序入口
35+
```
36+
37+
## 功能特点
38+
39+
- 简单且安全的 `HTTP` 基本认证
40+
- 自动处理认证头部
41+
- 可自定义认证领域消息
42+
- 清晰分离认证逻辑
43+
44+
## 安装设置
45+
46+
1. 克隆仓库:
47+
```bash
48+
git clone https://github.com/gogf/examples.git
49+
cd examples/httpserver/basic-auth
50+
```
51+
52+
2. 安装依赖:
53+
```bash
54+
go mod tidy
55+
```
56+
57+
3. 运行应用:
58+
```bash
59+
go run main.go
60+
```
61+
62+
## 使用方法
63+
64+
1. 启动服务器:
65+
```bash
66+
go run main.go
67+
```
68+
69+
2. 服务器将在 `8000` 端口启动。
70+
71+
3. 访问受保护的资源:
72+
- 网址:http://127.0.0.1:8000/
73+
- 当提示时,输入以下凭据:
74+
- 用户:`user`
75+
- 密码:`pass`
76+
77+
4. 认证成功后,您将看到消息:"`Authentication successful!`"
78+
79+
## 实现细节
80+
81+
服务器使用 `GoFrame``BasicAuth` 方法实现 `HTTP` 基本认证。该方法:
82+
83+
1. 检查请求是否包含有效的基本认证凭据
84+
2. 如果凭据缺失或无效,它会自动:
85+
- 设置带有指定领域的 `WWW-Authenticate` 头部
86+
- 返回 `401` 未授权状态码
87+
- 使浏览器显示认证对话框
88+
3. 如果认证成功,它返回 `true` 并允许处理程序继续处理受保护的内容
89+
90+
实现非常简洁,只需要很少的代码:
91+
92+
```go
93+
if r.BasicAuth("user", "pass", "Please enter username and password") {
94+
// 认证成功后的处理
95+
r.Response.Write("Authentication successful!")
96+
}
97+
// 如果认证失败,BasicAuth 方法会自动处理响应
98+
```
99+
100+
## 注意事项
101+
102+
- 基本认证以 `base64` 编码传输凭据,在纯 `HTTP` 上不安全
103+
- 在生产环境中,始终将基本认证与 `HTTPS` 结合使用
104+
- 本示例中的凭据是硬编码的,仅用于演示目的;在实际应用中,应使用安全的凭据存储

httpserver/basic-auth/go.mod

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
module main
2+
3+
go 1.20
4+
5+
require github.com/gogf/gf/v2 v2.8.3
6+
7+
require (
8+
github.com/BurntSushi/toml v1.4.0 // indirect
9+
github.com/clbanning/mxj/v2 v2.7.0 // indirect
10+
github.com/emirpasic/gods v1.18.1 // indirect
11+
github.com/fatih/color v1.18.0 // indirect
12+
github.com/fsnotify/fsnotify v1.7.0 // indirect
13+
github.com/go-logr/logr v1.4.2 // indirect
14+
github.com/go-logr/stdr v1.2.2 // indirect
15+
github.com/gorilla/websocket v1.5.3 // indirect
16+
github.com/grokify/html-strip-tags-go v0.1.0 // indirect
17+
github.com/magiconair/properties v1.8.9 // indirect
18+
github.com/mattn/go-colorable v0.1.13 // indirect
19+
github.com/mattn/go-isatty v0.0.20 // indirect
20+
github.com/mattn/go-runewidth v0.0.16 // indirect
21+
github.com/olekukonko/tablewriter v0.0.5 // indirect
22+
github.com/rivo/uniseg v0.4.7 // indirect
23+
go.opentelemetry.io/otel v1.24.0 // indirect
24+
go.opentelemetry.io/otel/metric v1.24.0 // indirect
25+
go.opentelemetry.io/otel/sdk v1.24.0 // indirect
26+
go.opentelemetry.io/otel/trace v1.24.0 // indirect
27+
golang.org/x/net v0.32.0 // indirect
28+
golang.org/x/sys v0.28.0 // indirect
29+
golang.org/x/text v0.21.0 // indirect
30+
gopkg.in/yaml.v3 v3.0.1 // indirect
31+
)

httpserver/basic-auth/go.sum

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
2+
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
3+
github.com/clbanning/mxj/v2 v2.7.0 h1:WA/La7UGCanFe5NpHF0Q3DNtnCsVoxbPKuyBNHWRyME=
4+
github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn/Qo+ve2s=
5+
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
6+
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
7+
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
8+
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
9+
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
10+
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
11+
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
12+
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
13+
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
14+
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
15+
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
16+
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
17+
github.com/gogf/gf/v2 v2.8.3 h1:h9Px3lqJnnH6It0AqHRz4/1hx0JmvaSf1IvUir5x1rA=
18+
github.com/gogf/gf/v2 v2.8.3/go.mod h1:n++xPYGUUMadw6IygLEgGZqc6y6DRLrJKg5kqCrPLWY=
19+
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
20+
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
21+
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
22+
github.com/grokify/html-strip-tags-go v0.1.0 h1:03UrQLjAny8xci+R+qjCce/MYnpNXCtgzltlQbOBae4=
23+
github.com/grokify/html-strip-tags-go v0.1.0/go.mod h1:ZdzgfHEzAfz9X6Xe5eBLVblWIxXfYSQ40S/VKrAOGpc=
24+
github.com/magiconair/properties v1.8.9 h1:nWcCbLq1N2v/cpNsy5WvQ37Fb+YElfq20WJ/a8RkpQM=
25+
github.com/magiconair/properties v1.8.9/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
26+
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
27+
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
28+
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
29+
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
30+
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
31+
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
32+
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
33+
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
34+
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
35+
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
36+
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
37+
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
38+
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
39+
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
40+
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
41+
go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo=
42+
go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo=
43+
go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI=
44+
go.opentelemetry.io/otel/metric v1.24.0/go.mod h1:VYhLe1rFfxuTXLgj4CBiyz+9WYBA8pNGJgDcSFRKBco=
45+
go.opentelemetry.io/otel/sdk v1.24.0 h1:YMPPDNymmQN3ZgczicBY3B6sf9n62Dlj9pWD3ucgoDw=
46+
go.opentelemetry.io/otel/sdk v1.24.0/go.mod h1:KVrIYw6tEubO9E96HQpcmpTKDVn9gdv35HoYiQWGDFg=
47+
go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI=
48+
go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU=
49+
golang.org/x/net v0.32.0 h1:ZqPmj8Kzc+Y6e0+skZsuACbx+wzMgo5MQsJh9Qd6aYI=
50+
golang.org/x/net v0.32.0/go.mod h1:CwU0IoeOlnQQWJ6ioyFrfRuomB8GKF6KbYXZVyeXNfs=
51+
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
52+
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
53+
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
54+
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
55+
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
56+
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
57+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
58+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
59+
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
60+
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

httpserver/basic-auth/main.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// examples/httpserver/basic-auth/main.go
2+
package main
3+
4+
import (
5+
"github.com/gogf/gf/v2/frame/g"
6+
"github.com/gogf/gf/v2/net/ghttp"
7+
)
8+
9+
// main is the entry point of the application.
10+
// It sets up an HTTP server with Basic Authentication protection.
11+
func main() {
12+
// Create a new server instance
13+
s := g.Server()
14+
15+
// Bind handler for the root path with Basic Authentication
16+
s.BindHandler("/", func(r *ghttp.Request) {
17+
// Check authentication credentials using BasicAuth method
18+
// If authentication succeeds, it returns true
19+
// If authentication fails, it automatically sends a 401 status code with WWW-Authenticate header
20+
// The third parameter is the realm message shown in the browser's authentication dialog
21+
if r.BasicAuth("user", "pass", "Please enter username and password") {
22+
// Process after successful authentication
23+
r.Response.Write("Authentication successful!")
24+
}
25+
// If authentication fails, the BasicAuth method handles the response automatically
26+
// No additional code is needed for the failure case
27+
})
28+
29+
// Set the server port
30+
s.SetPort(8000)
31+
32+
// Start the server
33+
s.Run()
34+
}

0 commit comments

Comments
 (0)