此版本主要加入了token續約功能並對緩存進行了優化,自此gtoken已完全可以支撐線上token認證,並支持集群模式;
基於gf框架的token插件,通過服務端驗證方式實現token認證;
# 配置文件
# 緩存模式 1 gcache 2 gredis
cache-mode = 2
// 註:通過MaxRefresh,默認當用戶第五天訪問時,自動再進行五天續期
// 超時時間 默認10天
Timeout int
// 緩存刷新時間 默認為超時時間的一半
MaxRefresh int
gopath模式: go get https://github.comgoflyfox/gtoken
或者 使用go.mod添加 :require github.comgoflyfox/gtoken last
只需要配置登錄路徑、登出路徑、攔截路徑以及登錄校驗實現即可
// 啟動gtoken gtoken := >oken.GfToken{ LoginPath: "/login", LoginBeforeFunc: loginFunc, LogoutPath: "/user/logout", AuthPaths: g.SliceStr{"/user/*", "/system/*"}, } gtoken.Start()
登錄方法實現
func Login(r *ghttp.Request) (string, interface{}) { username := r.GetPostString("username") passwd := r.GetPostString("passwd") // TODO 進行登錄校驗 return username, "" }
可運行api_test.go進行測試並查看結果;驗證邏輯說明:
--- PASS: TestSystemUser (0.00s) api_test.go:43: 1. not login and visit user api_test.go:50: {"code":-1,"data":"","msg":"query token fail"} api_test.go:63: 2. execute login and visit user api_test.go:66: {"code":0,"msg":"success","data":"system user"} api_test.go:72: 3. execute logout api_test.go:75: {"code":0,"msg":"success","data":"logout success"} api_test.go:81: 4. visit user api_test.go:86: {"code":-1,"msg":"login timeout or not login","data":""}
[admin
]