golang 每日一庫之 volatiletech-authboss
Authboss 是一個強大且可擴展的 Go 語言認證(authentication)和授權(authorization)框架,適用於 Web 應用程序。它提供了一套完整的用戶身份驗證方案,包括用戶註冊、登錄、註銷、賬號恢復、密碼重置、OAuth2、雙因素認證(2FA)等功能,使開發者能夠快速構建安全的身份認證系統。
核心特性
-
模塊化設計
:
Authboss由多個獨立的模塊組成,可按需啓用或禁用功能。 -
支持多種認證方式
:
-
用戶名 / 密碼登錄
-
OAuth2(Google, Facebook, GitHub 等)
-
雙因素認證(2FA)
-
會話管理
:支持 Cookie 和 Token 認證,可用於 API 或 Web 應用。
-
賬號管理
:
-
賬號註冊 / 註銷
-
電子郵件驗證
-
密碼重置
-
多數據庫支持
:適用於各種存儲後端(如 MySQL、PostgreSQL、MongoDB)。
-
擴展性強
:可以自定義存儲、用戶模型、模板等。
安裝
使用 go get 安裝 Authboss:
go get -u github.com/volatiletech/authboss/v3
基本使用
Authboss 需要進行初始化配置,包括:
-
用戶存儲(數據庫)
-
會話管理
-
視圖模板
-
啓用的模塊
1. 初始化 Authboss
package main
import (
"fmt"
"log"
"net/http"
"github.com/volatiletech/authboss/v3"
"github.com/volatiletech/authboss-clientstate/v3"
"github.com/volatiletech/authboss-renderer/v3"
)
func main() {
ab := authboss.New()
// 配置會話存儲
cookieStoreKey := []byte("your-secret-key")
ab.Config.Storage.Server = authboss.NewMemoryStore() // 使用內存存儲
ab.Config.Storage.SessionState = abclientstate.NewSessionState(cookieStoreKey, nil)
ab.Config.Storage.CookieState = abclientstate.NewCookieState(cookieStoreKey, nil)
// 配置模板渲染器
ab.Config.Core.ViewRenderer = abrenderer.NewHTML("./views")
// 啓用模塊(如註冊、登錄、密碼重置)
ab.Config.Modules.RegisterPreserveFields = []string{"email"}
ab.Config.Modules.RegisterAfterLoginRedirect = "/dashboard"
if err := ab.Init(); err != nil {
log.Fatal(err)
}
// 處理請求
mux := http.NewServeMux()
mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome to Authboss example!")
}))
mux.Handle("/auth/", http.StripPrefix("/auth", ab.Router()))
log.Println("Server running on :8080")
http.ListenAndServe(":8080", mux)
}
解析:
-
配置
Authboss實例,包括存儲、會話管理、模板渲染等。 -
啓用
authboss.NewMemoryStore()作爲存儲(可替換爲數據庫存儲)。 -
通過
ab.Router()處理/auth/相關的認證請求。
2. 用戶存儲(數據庫)
Authboss 需要用戶模型來存儲用戶數據,如用戶名、密碼哈希等。
定義用戶結構
type User struct {
ID string
Email string
Password string
}
實現 authboss.User 接口
func (u User) GetPID() string {
return u.Email
}
func (u User) GetPassword() string {
return u.Password
}
解析:
-
GetPID()返回用戶的唯一標識(通常是
Email或Username)。 -
GetPassword()返回加密後的密碼。
3. 自定義存儲(數據庫)
要存儲用戶信息,我們需要實現 authboss.Storage 接口:
type UserStore struct {
users map[string]User
}
func (s *UserStore) Load(pid string) (authboss.User, error) {
user, ok := s.users[pid]
if !ok {
return nil, authboss.ErrUserNotFound
}
return user, nil
}
func (s *UserStore) Save(user authboss.User) error {
u := user.(User)
s.users[u.Email] = u
return nil
}
解析:
-
Load(pid string)通過用戶 ID(郵箱)查找用戶。
-
Save(user authboss.User)存儲用戶信息。
然後,在 Authboss 配置中設置:
ab.Config.Storage.Server = &UserStore{users: make(map[string]User)}
4. 啓用常見認證功能
4.1 用戶註冊
用戶可以通過 /auth/register 進行註冊:
ab.Config.Modules.RegisterPreserveFields = []string{"email"}
ab.Config.Modules.RegisterAfterLoginRedirect = "/dashboard"
效果:
-
允許用戶註冊,並存儲
email字段。 -
註冊成功後跳轉到
/dashboard。
4.2 用戶登錄
Authboss 默認啓用了 /auth/login 端點:
ab.Config.Modules.LoginAfterRegistration = true
ab.Config.Modules.LoginAfterLoginRedirect = "/dashboard"
效果:
- 允許用戶登錄,登錄成功後跳轉到
/dashboard。
4.3 密碼重置
要啓用密碼重置功能:
ab.Config.Modules.RecoverLoginAfterRecovery = true
ab.Config.Modules.RecoverRedirectAfter = "/auth/login"
-
允許用戶請求密碼重置(郵件發送需要額外配置)。
-
重置完成後跳轉到
/auth/login。
5. OAuth2 認證
Authboss 還支持 OAuth2 登錄,如 Google、GitHub:
ab.Config.Modules.OAuth2Providers = map[string]authboss.OAuth2Provider{
"google": {
AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://oauth2.googleapis.com/token",
UserURL: "https://www.googleapis.com/oauth2/v2/userinfo",
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
Scopes: []string{"email"},
},
}
-
添加
OAuth2提供方,如 Google。 -
用戶可以通過
/auth/oauth2/google登錄。
6. 退出登錄
Authboss 提供了 /auth/logout 端點:
mux.Handle("/auth/logout", ab.Config.Core.LogoutHandler)
- 訪問
/auth/logout即可註銷用戶。
適用場景
-
Web 應用認證系統
(類似 Django/Auth、Devise)。
-
基於 OAuth2 的社交登錄(Google、GitHub、Facebook)
。
-
支持 API 認證(JWT、Session)
。
-
需要密碼找回、雙因素認證的系統
。
總結
Authboss 是一個強大的 Go 認證框架,提供了完整的用戶身份管理方案,適用於 Web 應用的用戶認證、OAuth2 社交登錄、雙因素認證等場景。它的模塊化設計讓開發者能夠按需啓用功能,並支持各種存儲後端,非常適合構建安全的身份認證系統。
標題:golang 每日一庫之 volatiletech/authboss
作者:mooncakeee
地址:http://blog.dd95828.com/articles/2025/03/16/1742099877566.html
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/NxifCLLvgfEpIbJnj37myg